Java Code Examples for javax.swing.JTextArea.getText()

The following are Jave code examples for showing how to use getText() of the javax.swing.JTextArea class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: EditCalculateAndChart   File: FindRight_Action.java   Source Code and License Vote up 6 votes
@Override
public void actionPerformed(ActionEvent e) {
     JTextArea area = TEdit.getTextArea();
     String txt = area.getText();
     if(txt == null)
         return;
     String s = TEdit.getLookingFor();
     if(s.contentEquals(""))
         return;
     if(txt.contentEquals("") || txt.length()<1)
         return;
      if(area.getCaretPosition() >=txt.length()-1){
          area.setCaretPosition(0);
          //JOptionPane.showMessageDialog(TEdit.getFrame(),"Reached the end of the text");
          //return;
      }
           int foundAt = txt.indexOf(s,area.getCaretPosition()+s.length());
           if(foundAt == -1){
               JOptionPane.showMessageDialog(TEdit.getFrame(),"Reached the end of the text");
               return;
           }
               area.setCaretPosition(foundAt);
               area.select(foundAt,foundAt+s.length());
}
 
Example 2
Project: powertext   File: BasicEvents.java   Source Code and License Vote up 6 votes
public static int SetCursor(int newlineno,JTextArea textPane)
{
    int pos = 0;
    int i = 0;
    String line = "";
    Scanner scanner = new Scanner(textPane.getText());
    while (scanner.hasNextLine())
    {
        line = scanner.nextLine();
        i++;
        if (newlineno > i)
        {
            pos = pos + line.length() + 1;
        }
    }
    return pos;
}
 
Example 3
Project: powertext   File: BasicEvents.java   Source Code and License Vote up 6 votes
public static int SetCursor(int newlineno,JTextArea textPane)
{
    int pos = 0;
    int i = 0;
    String line = "";
    Scanner scanner = new Scanner(textPane.getText());
    while (scanner.hasNextLine())
    {
        line = scanner.nextLine();
        i++;
        if (newlineno > i)
        {
            pos = pos + line.length() + 1;
        }
    }
    return pos;
}
 
Example 4
Project: powertext   File: SearchEngine.java   Source Code and License Vote up 6 votes
/**
 * Returns the text in which to search, as a string.  This is used
 * internally to grab the smallest buffer possible in which to search.
 */
private static String getFindInText(JTextArea textArea, int start,
								boolean forward) {

	// Be smart about the text we grab to search in.  We grab more than
	// a single line because our searches can return multi-line results.
	// We copy only the chars that will be searched through.
	String findIn = null;
	try {
		if (forward) {
			findIn = textArea.getText(start,
						textArea.getDocument().getLength()-start);
		}
		else { // backward
			findIn = textArea.getText(0, start);
		}
	} catch (BadLocationException ble) {
		// Never happens; findIn will be null anyway.
		ble.printStackTrace();
	}

	return findIn;

}
 
Example 5
Project: EditCalculateAndChart   File: FindLeft_Action.java   Source Code and License Vote up 5 votes
@Override
public void actionPerformed(ActionEvent e) {
     JTextArea area = TEdit.getTextArea();
     String txt = area.getText();
     if(txt == null)
         return;
     String s = TEdit.getLookingFor();
     if(s.contentEquals(""))
         return;
     if(txt.contentEquals("") || txt.length()<1)
         return;
     if(area.getCaretPosition() < s.length()-1){
          JOptionPane.showMessageDialog(TEdit.getFrame(),"Reached the beginning of the text");
          return;
      }
           if(area.getCaretPosition()-s.length()<=0){
               area.setCaretPosition(txt.length()-1);
           }
           int foundAt = txt.substring(0,area.getCaretPosition()-s.length()).lastIndexOf(s);
           
           if(foundAt == -1){
               JOptionPane.showMessageDialog(TEdit.getFrame(),"Reached the beginning of the text");
               return;
           }
               area.setCaretPosition(foundAt);
               area.select(foundAt,foundAt+s.length());
}
 
Example 6
Project: ramus   File: MovingArea.java   Source Code and License Vote up 5 votes
public void createBlocksFromLines() {

        final JTextArea textArea = new JTextArea();

        BaseDialog dialog = new BaseDialog(getPanel().getFramework()
                .getMainFrame()) {
            @Override
            protected void onOk() {
                if (textArea.getText().trim().length() > 0) {
                    StringTokenizer st = new StringTokenizer(
                            textArea.getText(), "\n");
                    List<String> strings = new ArrayList<String>();

                    while (st.hasMoreElements()) {
                        String s = st.nextToken().trim();
                        if (s.length() > 0)
                            strings.add(s);
                    }
                    startUserTransaction();
                    createBlocks(strings.toArray(new String[strings.size()]));
                    commitUserTransaction();
                    super.onOk();
                }
            }
        };

        dialog.setMainPane(new JScrollPane(textArea));

        ResourceLoader.setJComponentsText(dialog);

        dialog.setBounds(0, 0, 800, 600);
        dialog.setLocationRelativeTo(null);

        dialog.setVisible(true);
    }
 
Example 7
Project: powertext   File: BasicEvents.java   Source Code and License Vote up 5 votes
public static int getLineCount(JTextArea textPane)
{
    _lineCount = 0;
    Scanner scanner = new Scanner(textPane.getText());
    while (scanner.hasNextLine())
    {
        String line = scanner.nextLine();
        _lineCount++;
    }
    return _lineCount;
}
 
Example 8
Project: powertext   File: summary.java   Source Code and License Vote up 5 votes
public static void summaryAll() throws IOException{
    int sel = jTabbedPane1.getSelectedIndex();
    jLabel23.setText(jTabbedPane1.getTitleAt(sel));
    jLabel24.setText("File Location : " + titleText.getText());
    /**String[] {splitStrings = filesave.getSelectedFile().getName().split("\\.") ;
        String extension = splitStrings[splitStrings.length-1] ;
        fileext.setText(extension);}**/
    jLabel16.setText("File Extention : " + titleExtLa.getText());
    JTextArea textPane = (JTextArea) ((JScrollPane) ((JDesktopPane)jTabbedPane1.getComponentAt(sel)).getComponent(0)).getViewport().getComponent(0);
    String totaltext=  textPane.getText();
    String totalwords[]=totaltext.split("\\s");  
    jLabel21.setText("Total Word Typed : " + totalwords.length);
    jLabel5.setText("Total Characters With Spaces : " + totaltext.length());
    jLabel22.setText("Total Line : " + BasicEvents.getLineCount(textPane));
	if (titleText.getText().contains("Untitled")) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
            Calendar cal = Calendar.getInstance();
        jLabel27.setText(dateFormat.format(cal.getTime())); 
        jLabel25.setText(dateFormat.format(cal.getTime()));
    } else {
        Path filepath = Paths.get(titleText.getText()) ;
        BasicFileAttributes attr = Files.readAttributes(filepath, BasicFileAttributes.class);
            String dateCreate = ""+attr.creationTime() ; String dateCreat = dateCreate.replace("T", "  Time Created : ");
            String lastModi = ""+attr.lastModifiedTime() ; String lastMod = lastModi.replace("T", "  Last Time Modified : ");
             jLabel25.setText("Date Created : " + dateCreat );
            jLabel27.setText("Last Date Modified : " + lastMod );
    }
}
 
Example 9
Project: powertext   File: BasicEvents.java   Source Code and License Vote up 5 votes
public static int getLineCount(JTextArea textPane)
{
    _lineCount = 0;
    Scanner scanner = new Scanner(textPane.getText());
    while (scanner.hasNextLine())
    {
        String line = scanner.nextLine();
        _lineCount++;
    }
    return _lineCount;
}
 
Example 10
Project: powertext   File: summary.java   Source Code and License Vote up 5 votes
public static void summaryAll() throws IOException{
    int sel = jTabbedPane1.getSelectedIndex();
    jLabel23.setText(jTabbedPane1.getTitleAt(sel));
    jLabel24.setText("File Location : " + titleText.getText());
    /**String[] {splitStrings = filesave.getSelectedFile().getName().split("\\.") ;
        String extension = splitStrings[splitStrings.length-1] ;
        fileext.setText(extension);}**/
    jLabel16.setText("File Extention : " + titleExtLa.getText());
    JTextArea textPane = (JTextArea) ((JScrollPane) ((JDesktopPane)jTabbedPane1.getComponentAt(sel)).getComponent(0)).getViewport().getComponent(0);
    String totaltext=  textPane.getText();
    String totalwords[]=totaltext.split("\\s");  
    jLabel21.setText("Total Word Typed : " + totalwords.length);
    jLabel5.setText("Total Characters With Spaces : " + totaltext.length());
    jLabel22.setText("Total Line : " + BasicEvents.getLineCount(textPane));
	if (titleText.getText().contains("Untitled")) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
            Calendar cal = Calendar.getInstance();
        jLabel27.setText(dateFormat.format(cal.getTime())); 
        jLabel25.setText(dateFormat.format(cal.getTime()));
    } else {
        Path filepath = Paths.get(titleText.getText()) ;
        BasicFileAttributes attr = Files.readAttributes(filepath, BasicFileAttributes.class);
            String dateCreate = ""+attr.creationTime() ; String dateCreat = dateCreate.replace("T", "  Time Created : ");
            String lastModi = ""+attr.lastModifiedTime() ; String lastMod = lastModi.replace("T", "  Last Time Modified : ");
             jLabel25.setText("Date Created : " + dateCreat );
            jLabel27.setText("Last Date Modified : " + lastMod );
    }
}
 
Example 11
Project: java-course   File: SortLinesDescendingAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos;

        String text = currentEditor.getText(fromPos, length);
        text = sortLinesDesc(text);
        document.remove(fromPos, length);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(fromPos + length);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }

}
 
Example 12
Project: java-course   File: SortLinesAscendingAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos;

        String text = currentEditor.getText(fromPos, length);
        text = sortLinesAsc(text);
        document.remove(fromPos, length);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(fromPos + length);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }

}
 
Example 13
Project: java-course   File: UniqueLinesAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos + 1;

        String text = currentEditor.getText(fromPos, length);
        text = removeLines(text);
        document.remove(fromPos, length - 1);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(length - 1);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }
}
 
Example 14
Project: incubator-netbeans   File: RepositorySelectorTest.java   Source Code and License Vote up 4 votes
private String getErrroLabelText(SelectorPanel sp) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    RepositorySelectorBuilder builder = (RepositorySelectorBuilder) getField(sp, "builder");
    RepositoryFormPanel form = (RepositoryFormPanel) getField(builder, "repositoryFormsPanel");
    JTextArea label = (JTextArea) getField(form, "errorText");
    return label.getText();
}
 
Example 15
Project: EditCalculateAndChart   File: Replace_Action.java   Source Code and License Vote up 4 votes
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea area = TEdit.getTextArea();
    if(area.getText().length()==0){
        JOptionPane.showMessageDialog(TEdit.getFrame(),"There is nothing to replace!");
        return;
    }
    JTextField source = new JTextField();
    JTextField target = new JTextField();
    Object[] message = {
                          "Source:", source,
                          "Target:", target
                        };
    int option = JOptionPane.showConfirmDialog(TEdit.getFrame(), message, "Replace", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,myIcon);
    if (option != JOptionPane.OK_OPTION)
        return;
    
    String src = source.getText();
    String trgt= target.getText();
    
    if(src.contentEquals(""))
            return;
    
             Highlighter hilite = area.getHighlighter();
     Highlighter.Highlight[] hilites = hilite.getHighlights();
     int Shift=0;
     String txt=area.getText();
     if(hilites != null && hilites.length >0){ 
         for (Highlighter.Highlight hilite1 : hilites) {
                //txt.substring(hilite1.getStartOffset(), hilite1.getEndOffset()))
               area.replaceRange(txt.substring(hilite1.getStartOffset(), hilite1.getEndOffset()).replace(src,trgt),
                              hilite1.getStartOffset()-Shift, hilite1.getEndOffset()-Shift);
               Shift = Shift -(src.length()-trgt.length());
         }
        
     }
     else{
         txt=txt.replace(src,trgt);
         area.setText(txt);
     }
            
            
    
     
}
 
Example 16
Project: jdk8u-jdk   File: WrongKeyTypedConsumedTest.java   Source Code and License Vote up 4 votes
public void start ()
{
    setSize (200,200);
    setVisible(true);
    validate();

    JFrame frame = new JFrame("The Frame");
    Set ftk = new HashSet();
    ftk.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0));
    frame.getContentPane().
        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                              ftk);

    JCheckBox checkbox = new JCheckBox("test");
    frame.getContentPane().add(checkbox, BorderLayout.NORTH);

    JTextArea textarea = new JTextArea(40, 10);
    frame.getContentPane().add(textarea);

    frame.pack();
    frame.setVisible(true);
    Util.waitForIdle(robot);

    if (!frame.isActive()) {
        throw new RuntimeException("Test Fialed: frame isn't active");
    }

    // verify if checkbox has focus
    if (!checkbox.isFocusOwner()) {
        checkbox.requestFocusInWindow();
        Util.waitForIdle(robot);
        if (!checkbox.isFocusOwner()) {
            throw new RuntimeException("Test Failed: checkbox doesn't have focus");
        }
    }

    // press VK_DOWN
    robot.keyPress(KeyEvent.VK_DOWN);
    robot.delay(50);
    robot.keyRelease(KeyEvent.VK_DOWN);
    robot.delay(50);

    Util.waitForIdle(robot);

    // verify if text area has focus
    if (!textarea.isFocusOwner()) {
        throw new RuntimeException("Test Failed: focus wasn't transfered to text area");
    }
    // press '1'
    robot.keyPress(KeyEvent.VK_1);
    robot.delay(50);
    robot.keyRelease(KeyEvent.VK_1);
    robot.delay(50);

    Util.waitForIdle(robot);

    // verify if KEY_TYPED arrived
    if (!"1".equals(textarea.getText())) {
        throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\"");
    }
    System.out.println("Test Passed");
}
 
Example 17
Project: iTrace-Archive   File: SessionInfoHandler.java   Source Code and License Vote up 4 votes
protected void sessionUI() {
	setSessionID();
	//textfields needed for UI
	JTextField sessionIDText = new JTextField(getSessionID());
	sessionIDText.setEditable(false);
	JTextArea sessionDescripText = new JTextArea(4,5);
	sessionDescripText.setLineWrap(true);
	JScrollPane scrollPane = new JScrollPane(sessionDescripText);
       
	//Radio Button List
	JRadioButton newFeature = new JRadioButton("New Feature");
	JRadioButton bugFix = new JRadioButton("Bug Fix");
	JRadioButton refactoring = new JRadioButton("Refactoring");
	JRadioButton genComp = new JRadioButton("General Comprehension");
	JRadioButton other = new JRadioButton("Other");
	
	//Group the buttons
	ButtonGroup radioList = new ButtonGroup();
	radioList.add(newFeature);
	radioList.add(bugFix);
	radioList.add(refactoring);
	radioList.add(genComp);
	radioList.add(other);
	
	//Add to a JPanel
	JPanel radioPanel = new JPanel(new GridLayout(0, 1));
	radioPanel.add(newFeature);
	radioPanel.add(bugFix);
	radioPanel.add(refactoring);
	radioPanel.add(genComp);
	radioPanel.add(other);
	
	//Add everything to main JPanel
	JPanel sessionPanel = new JPanel(); //main panel
	sessionPanel.setLayout(new GridBagLayout());
	GridBagConstraints c = new GridBagConstraints();
	c.fill = GridBagConstraints.NONE;
	c.anchor = GridBagConstraints.NORTHWEST;
	
	c.gridx = 0;
	c.gridy = 0;
	sessionPanel.add(new JLabel("Generated Session ID:"),c);
	c.gridx++;
	sessionPanel.add(sessionIDText,c);
	c.gridx = 0;
	c.gridy++;
	sessionPanel.add(new JLabel("Session Purpose (select one):"),c);
	c.gridx++;
	sessionPanel.add(radioPanel,c);
	c.gridx = 0;
	c.gridy++;
	sessionPanel.add(new JLabel("Enter the Session Description:"),c);
	c.gridx++;
	c.fill = GridBagConstraints.HORIZONTAL;
	sessionPanel.add(scrollPane,c);
	
	final int selection = JOptionPane.showConfirmDialog(null, sessionPanel, 
			"Enter the Current Session Info.",
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
	if (selection == JOptionPane.OK_OPTION) {
		sessionDescrip = sessionDescripText.getText();
		if (newFeature.isSelected()) {
			sessionPurpose = newFeature.getText();
		} else if (bugFix.isSelected()) {
			sessionPurpose = bugFix.getText();
		} else if (refactoring.isSelected()) {
			sessionPurpose = refactoring.getText();
		} else if (genComp.isSelected()) {
			sessionPurpose = genComp.getText();
		} else if (other.isSelected()) {
			sessionPurpose = other.getText();
		} else {
			sessionPurpose = new String();
			System.out.println("Warning! "
					+ "Your Session Purpose has not been selected.");
		}
		hasSessionInfo = true;
	}  
}
 
Example 18
Project: openjdk-jdk10   File: WrongKeyTypedConsumedTest.java   Source Code and License Vote up 4 votes
public void start ()
{
    setSize (200,200);
    setVisible(true);
    validate();

    JFrame frame = new JFrame("The Frame");
    Set ftk = new HashSet();
    ftk.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0));
    frame.getContentPane().
        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                              ftk);

    JCheckBox checkbox = new JCheckBox("test");
    frame.getContentPane().add(checkbox, BorderLayout.NORTH);

    JTextArea textarea = new JTextArea(40, 10);
    frame.getContentPane().add(textarea);

    frame.pack();
    frame.setVisible(true);
    Util.waitForIdle(robot);

    if (!frame.isActive()) {
        throw new RuntimeException("Test Fialed: frame isn't active");
    }

    // verify if checkbox has focus
    if (!checkbox.isFocusOwner()) {
        checkbox.requestFocusInWindow();
        Util.waitForIdle(robot);
        if (!checkbox.isFocusOwner()) {
            throw new RuntimeException("Test Failed: checkbox doesn't have focus");
        }
    }

    // press VK_DOWN
    robot.keyPress(KeyEvent.VK_DOWN);
    robot.delay(50);
    robot.keyRelease(KeyEvent.VK_DOWN);
    robot.delay(50);

    Util.waitForIdle(robot);

    // verify if text area has focus
    if (!textarea.isFocusOwner()) {
        throw new RuntimeException("Test Failed: focus wasn't transfered to text area");
    }
    // press '1'
    robot.keyPress(KeyEvent.VK_1);
    robot.delay(50);
    robot.keyRelease(KeyEvent.VK_1);
    robot.delay(50);

    Util.waitForIdle(robot);

    // verify if KEY_TYPED arrived
    if (!"1".equals(textarea.getText())) {
        throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\"");
    }
    System.out.println("Test Passed");
}