Selection in JTextArea

Hi all,
I want to select a part of the words in my JTextArea. But not with the mouse, my programm has to select. I use the method select(int, int) from javax.swing.text.JTextComponent. It works, becouse if I make cut selection the part will be cut. But I also want to SEE what is selected, like it looks like when i select something with the mouse.
What can I do?
THX
foxy

textComponent.setSelectionStart(int);
textComponent.setSelectionEnd(int);

Similar Messages

  • Block selection in JTextArea

    Hi,
    I was wondering if there is anything built-in to Swing to implement a block selection in a text area.
    I understand that the concept of block selection is really only applicable when a fixed-width font is used. and since the text is represented as a flow of characters, the concept of block selection might not be readily available.
    If anyone know of any ways this can be done that will be great. Thank for your help in advance.
    Kit
    PS. In case it is not clear what block selection is, think of the selection behavior in Excel.

    You can implement KeyListener where use similar approach.
    best regards
    Stas
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestPopup
    JFrame frame;
    public static void main(String args[])
    new TestPopup();
    public TestPopup()
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextArea ta=new JTextArea("test11111\ntest22222\ntest33333\ntest44444\ntest55555\n");
    try {
    ta.getHighlighter().addHighlight(14,17,((DefaultHighlighter)ta.getHighlighter()).DefaultPainter);
    ta.getHighlighter().addHighlight(24,27,((DefaultHighlighter)ta.getHighlighter()).DefaultPainter);
    ta.getHighlighter().addHighlight(34,37,((DefaultHighlighter)ta.getHighlighter()).DefaultPainter);
    catch (Exception ex) {
    ex.printStackTrace();
    JScrollPane scroll=new JScrollPane(ta);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(scroll,BorderLayout.CENTER);
    frame.setSize(300,200);
    frame.setVisible(true);

  • Re: Vertical Selection in JTextArea

    How do I get a vertical selection (i.e. by columns) in a JTextArea? I'm trying to recreate the behaviour of the old DOS 'e' editor or Kate from KDE on Linux.
    I would also like to be able to cut copy and paste as colums, rather than rows.
    Thanks in Advance.

    textComponent.setSelectionStart(int);
    textComponent.setSelectionEnd(int);

  • About select() in JTextArea?

    i wrote the following codes,but the select() didnt work, :( why?
    could you help me?please....
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    public class TrySelect {
         * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame frame = new JFrame("TrySelect");
              Container c = frame.getContentPane();
              final JTextArea t= new JTextArea();
              c.add(t);
              JButton b = new JButton("Select");
              c.add(b,BorderLayout.SOUTH);
              b.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        t.select(5, 10);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setBounds(120, 200,400,500);
         frame.setVisible(true);
    thanks a lot!

    If the problem exactly is to get the data from the TextArea you have to use "getText()".
    Also mention number of rows and columns that the TextArea should contain while defining Text Area.
    JTextArea t = new JTextArea(5,10);
    This statement creates the TextArea with 5 rows and 10 cols.
    In order to get the data entered in the TextArea when the button pressed, use the following statement in "actionPerformed()".
    String str = t.getText();

  • To refresh the contents in JTextArea on selection of a row in JTable.

    This is the block of code that i have tried :
    import java.awt.GridBagConstraints;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import ui.layouts.ComponentsBox;
    import ui.layouts.GridPanel;
    import ui.layouts.LayoutConstants;
    import util.ui.UIUtil;
    public class ElectronicJournal extends GridPanel {
         private boolean DEBUG = false;
         private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
         private GridPanel jGPanel = new GridPanel();
         private GridPanel jGPanel1 = new GridPanel();
         private GridPanel jGPanel2 = new GridPanel();
         DefaultTableModel model;
         private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
         private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
         private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
         private JTextArea textArea = new JTextArea();
         private JScrollPane spTimeEntryView = new JScrollPane();
         private JScrollPane pan = new JScrollPane();
         String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
         private JButton jBtnExporttoExcel = UIUtil.getButton(85,
                   "Export to Excel - F2", "");
         final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
                   "Description" };
         final Object[][] data = {
                   { "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
                   { "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
         final String[] colHeads1 = {"Detailed View" };
         final Object[][] data1 = {
                   { "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
         JTable jtblTimeEntry = new JTable(data, colHeads);
         JTable jTbl1 = new JTable(data1,colHeads1);
         ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
         public ElectronicJournal() {
              super();
              jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
    textArea.append("asd \n 123 \n");
    } else {
         jtblTimeEntry.setRowSelectionAllowed(false);
              if (DEBUG) {
                   jtblTimeEntry.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
         printDebugData(jtblTimeEntry);
              initialize();
         private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
         private void initialize() {
              this.setSize(680, 200);
              this.setBackground(java.awt.SystemColor.control);
              jBtnExporttoExcel.setBackground(SystemColor.control);
              ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
              cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
              jpBoxButton.add(cmpRibbonHORZ);
              this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
              jGPanel.setSize(650, 91);
              jGPanel.setBackground(SystemColor.control);
              jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
              jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
              jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
              jGPanel1.setBackground(SystemColor.control);
              jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              spTimeEntryView.setViewportView(jtblTimeEntry);
              jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
                        GridBagConstraints.BOTH);
              jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
              jGPanel2.setBackground(SystemColor.control);
              jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              //textArea.setText(html);
              pan.setViewportView(textArea);
         int selectedRow = jTbl1.getSelectedRow();
              System.out.println("selectedRow ::" +selectedRow);
              int colCount = jTbl1.getColumnCount();
              System.out.println("colCount ::" +colCount);
              StringBuffer buf = new StringBuffer();
              System.out.println("Out Of For");
              /*for(int count =0;count<colCount;count++)
              {System.out.println("Inside For");
              buf.append(jTbl1.getValueAt(selectedRow,count));
              // method 1 : Constructs a new text area with the specified text. 
              textArea  =new JTextArea(buf.toString());
              //method 2 :To Append the given string to the text area's current text.   
             textArea.append(buf.toString());
              jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
              this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
                        GridBagConstraints.CENTER);
    This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
    Message was edited by: Samyuktha
    Samyuktha

    Please help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
    Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area.

  • Selection problem in rendered JtextArea.

    I create a jtable by rendering one column using jTextarea. While selecting the row, color of selection not geting to the rendered Jtextarea. How can i solve this problem.
    please help me

    Do you include code in your getTableCellRendererComponent method to change
    the color depending on if the row is selected or not? You'll need something like
         if ( isSelected ) {
              setForeground( table.getSelectionForeground() );
              setBackground( table.getSelectionBackground() );
         } else {
              setForeground( table.getForeground() );
              setBackground( table.getBackground() );
         }: jay

  • Selection problem in JTextArea

    hi all
    i have a TextArea in which i have some coded charecters in a group of ten charactes i treet these ten characters as a single character ,so when i delete or insert these charactes all these charactes r deleted and no other character r inserted in between , i do it with the caretListener,
    But the problem which i face is on the selection i want to select these characters as when we select some part of the URL then it is selected completely.
    help in the prob.

    this might work
    paste some text into the textArea (ensure it contains a sequence "12345")
    click anywhere in area of 12345
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    class Testing extends JFrame
      String specialChars = "12345";
      boolean settingCaret = false;
      public Testing()
        setSize(200,200);
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final JTextArea ta = new JTextArea(10,10);
        JScrollPane sp = new JScrollPane(ta);
        sp.setPreferredSize(new Dimension(175,150));
        JPanel jp = new JPanel();
        jp.add(sp);
        getContentPane().add(jp);
        pack();
        ta.addCaretListener(new CaretListener(){
          public void caretUpdate(CaretEvent ce){
            if(settingCaret == false)
              int startPos = ta.getText().indexOf(specialChars);
              if(startPos > -1)
                if(ta.getCaretPosition() >= startPos && ta.getCaretPosition() <= startPos+specialChars.length())
                  settingCaret = true;
                  ta.setSelectionStart(startPos);
                  ta.setSelectionEnd(startPos+specialChars.length());
                settingCaret = false;
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to write selected text in JTextArea in selected location

    iam using JTextArea ...
    i want to writer selected text in selected location,,,,,,

    use
    JTextArea.getSelectedText() and
    JTextArea.replaceRange(String str, int start, int end)
    methods.

  • Why JTextArea.select(int,int) not Highlight in java 1.4

    Hi guys
    Does anybody know why JTextArea.select(int, int) not Highlight the selected text in java 1.4. But java 1.3 works. Does java 1.4 change to use other method to hightlight the selected text in JTextArea? Thanks in advance.
    Regards,
    Mark.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SelTest extends JPanel {
      private JTextArea area;
      public SelTest() {
        setLayout( new BorderLayout() );
        area = new JTextArea( "This is a sample text", 20, 20 );
        JButton btn = new JButton( "Select" );
        btn.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent ae ){
            selectText2();
        add( area, BorderLayout.CENTER );
        add( btn, BorderLayout.SOUTH );
      private void selectText2(){
        area.requestFocus(); // MOST IMPORTANT
        area.select( 1, 4 );
        System.out.println("selcted : " + area.getSelectedText() );
      public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        f.getContentPane().add( new SelTest() );
        f.pack();
        f.setVisible( true );
    }

  • JTextArea artifacts when selecting/deselecting text

    I just bumped up against a font rendering issue with JTextArea. I have no doubt that it's a bug, but does anyone know of a workaround?
    Run the program below and select/deselect text by double-clicking words. The text is painted in a different location when selected and deselected. Try selecting by dragging the mouse or pressing shift and left/right arrow keys -- same problem, but the actual pixel location of the artifacts sometimes differs depending on the selection start and end, and the way the text was selected (keyboard/mouse drag/double click).
    Now try selecting the last word ("dog") by double clicking.import java.awt.Font;
    import java.awt.font.TextAttribute;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class TextAreaProblem {
      public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new TextAreaProblem().makeUI();
      public void makeUI() {
        Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
        attributes.put(TextAttribute.FAMILY, "Arial");
        attributes.put(TextAttribute.SIZE, 36.0);
        attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
        attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_LOOSE);
        Font font = Font.getFont(attributes);
        font = font.deriveFont(attributes);
        final JTextArea textArea = new JTextArea("The quick brown fox jumps over the lazy dog.");
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(textArea));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(850, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    Microsoft Windows [Version 6.1.7600]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
    C:\Users\Darryl>java -version
    java version "1.6.0_17"
    Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
    Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)Any tips for a workaround will be much appreciated.
    Thanks, Darryl

    The fix using System.setProperty worked 100% for all font and attribute combinations I tried -- thanks again.
    2) Does it work to set the property after the GUI is already created and shown? (shall test that myself in a few hours, but would be nice to know earlier :)No. However, you may set this property as a component client property (on the JTextComponent), but before that component is made visible.This didn't work for me. I tried both putClientProperty and getDocument().putProperty, as suggested in the other thread. What did I miss?import java.awt.Font;
    import java.awt.font.TextAttribute;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class TextAreaProblem {
      public static void main(String[] args) throws Exception {
        //System.setProperty("i18n", Boolean.TRUE.toString());
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new TextAreaProblem().makeUI();
      public void makeUI() {
        Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
        attributes.put(TextAttribute.FAMILY, "Arial");
        attributes.put(TextAttribute.SIZE, 36.0);
        attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_LOOSE);
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        Font font = Font.getFont(attributes);
        font = font.deriveFont(attributes);
        final JTextArea textArea = new JTextArea("The quick brown fox jumps over the lazy dog.");
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        // tried either or both -- didn't help
        textArea.getDocument().putProperty("i18n", Boolean.TRUE.toString());
        textArea.putClientProperty("i18n", Boolean.TRUE.toString());
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(textArea));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(850, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }Darryl
    edit Setting this property seems to remove the ability to render underlined and strikethrough attributes. Changed the code above to add these. When "i18n" is set, they are ignored.
    edit2 GlyphPainter2 also doesn't appear to support foreground/background colors and swap_colors. It's beginning to look like whoever wrote that class solved a single problem of cumulative integer math error but introduced several others. Or maybe just didn't reimplement the features that weren't inherited..
    Edited by: DarrylBurke on Sep 8, 2010 5:13 AM

  • Selecting Text in a JTextArea

    Hi, I have this problem with the JTextArea Caret positioning behaviour.
    I wanna select some text when I click (click, no dragging included) on a line. I use setcaretposition in the beggining of the line and movecaretposition in the end of the line.
    Nothing happens!!
    If I click the mouse and drag it a little bit then it works fine selecting the text showing the right colors and everything.
    I tried with the addhighlight method in the higlighter instance of JTextArea but it doesn't really select it, just changes it color.
    What do I have to do so that I can select text without having to drag when I click??
    Thaks a lot

    This shows you how to do it using a right click:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TextAreaTest extends JFrame
         JTextArea textArea;
         JScrollPane scrollPane;
         public TextAreaTest()
              textArea = new JTextArea( "one two\nthree four", 10, 30 )
                   //  the tab character is not inserted into the text area
                   public boolean isManagingFocus()
                        return false;
              textArea.setLineWrap( true );
              textArea.setSize( textArea.getPreferredSize() );
              textArea.setSelectionColor( Color.red );
              textArea.setSelectedTextColor( Color.green );
              try
                   System.out.println( textArea.modelToView( 4 ) );
                   System.out.println( Utilities.getRowStart(textArea, 4) );
              catch (Exception e) {}
              textArea.addMouseListener( new MouseAdapter()
                   public void mouseClicked(MouseEvent e)
                        if ( SwingUtilities.isRightMouseButton(e) )
                             try
                                  int offset = textArea.viewToModel( e.getPoint() );
                                  System.out.println( textArea.modelToView( offset ) );
                                  int start = Utilities.getWordStart(textArea, offset);
                                  int end = Utilities.getWordEnd(textArea, offset);
                                  String word = textArea.getDocument().getText(start, end-start);
                                  System.out.println( "Selected word: " + word );
                                  int rowStart = Utilities.getRowStart(textArea, offset);
                                  int rowEnd = Utilities.getRowEnd(textArea, offset);
                                  System.out.println( "Row start offset: " + rowStart );
                                  System.out.println( "Row end   offset: " + rowEnd );
                                  textArea.select(rowStart, rowEnd);
                             catch (Exception e2) {}
              textArea.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        int caretPosition = textArea.getCaretPosition();
                        Element root = textArea.getDocument().getDefaultRootElement();
                        int row = root.getElementIndex( caretPosition );
                        int column = caretPosition - root.getElement( row ).getStartOffset();
                        System.out.println( "Row   : " + ( row + 1 ) );
                        System.out.println( "Column: " + ( column + 1 ) );
              textArea.addKeyListener( new KeyAdapter()
                   public void keyPressed(KeyEvent e)
                        System.out.println( textArea.getDocument().getDefaultRootElement().getElementCount() );
              scrollPane = new JScrollPane( textArea );
              getContentPane().add( scrollPane );
              getContentPane().add( new JTextField(10),BorderLayout.SOUTH );
    //          textArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "" );
         public static void main(String[] args)
              TextAreaTest frame = new TextAreaTest();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • How to select multiple substring in JTextarea at the same time?

    I want to select multiple substring in a jtextarea at the same time by select(start,end) method, turns out only the last substring is highlighted, how to implement my goal?

    jamesybaby wrote:
    What you got so far? A SCCEE would be nice?my aim is to search key words in jtextarea and highlight all matched result.
    package frame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class FrmSelect extends JFrame {
        public FrmSelect() throws HeadlessException {
            setSize(800, 600);
            final JTextField tfKey = new JTextField();
            tfKey.setPreferredSize(new Dimension(200, 20));
            final JTextArea taContent = new JTextArea();
            JScrollPane jsp = new JScrollPane(taContent);
            tfKey.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String key = tfKey.getText();
                    String content = taContent.getText();
                    String[] splited = content.split(key);
                    Pattern ptn = Pattern.compile(key, Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);
                    Matcher matcher = ptn.matcher(content);
                    taContent.requestFocusInWindow();
                    while (matcher.find()) {
                        int start = matcher.start();
                        int end = matcher.end();
                        taContent.select(start, end);
            add(tfKey,BorderLayout.SOUTH);
            add(jsp,BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        public static void main(String[] args) {
             new FrmSelect();
    }please copy below into the jtextarea and type key 'prop' in the jtextfield, press return.
    prop1adsfasfd
    prop2adsfasdfadsf
    prop3asdfasdfasdf

  • How do i display an sql SELECT query in a jtextarea?

    Hi,
    I have a program that takes any SQL string from an inputArea JtextArea and displays "command executed successfuly" in the outputArea JTextArea if it works.
    My question is how do i make the outputArea display the actual query of the SELECT statment? Thanks!
            public void create(String SQLCommand) {
                   String query = SQLCommand;
                   try {
                       Statement stmt = con.createStatement();
                       ResultSet rs = stmt.executeQuery(query);
                       outputArea.setText("Command Executed Sucessfully: \n" + query);
                       rs.close();
                       stmt.close();
                   } catch (SQLException sqlex) {
                       outputArea.setText("Unable to Execute Command: \n" + query);
                       sqlex.printStackTrace();
            }

    It's a variation of the sample code I provided on the last post. Use a Vector of Vector of Objects to store the result set data (row and column data) and use another Vector to store the column names (for the JTable header). Then use the JTable constructor that accepts two Vector parameters to create your table. Eventually you'll want to customize your JTable by creating your own table model and custom cell editor and renderer. For now the sample code below will suffice.
    For more on using JTable see the following:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Vector header = new Vector();
    Vector result = new Vector();
    int columns = rsmd.getColumnCount();
    /* Retrieve column names */
    for (int i = 1; i <= columns; i++)
      header.add(rsmd.getColumnName(i));
    while (rs.next())
    Vector  row = new Vector();
    /* Columns numbers offset from one */  
    for (int i = 1; i <= columns; i++) 
       row.add(rs.getObject(i));  
    result.add(row);
    JTable table = new JTable(result,header);

  • Select part of jtextarea content over a button click

    Hi,
    i would like to do something quite simple, but i don't manage to do it and don't understand why my code doesn't work :s
    Actually, i would like to select a part of the text contained in a jtextarea when the user clicks over a jbutton ; here is my code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    public class BasicFrame extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         private JTextArea jta;
         private JButton b;
         public BasicFrame() {
              this.setSize(400,400);
              this.getContentPane().setLayout(new GridLayout(2,1));
              this.getContentPane().add(this.jta = new JTextArea());
              this.getContentPane().add(this.b = new JButton("foo"));
              this.b.addActionListener(this);
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setLocationRelativeTo(null);
         @Override
         public void actionPerformed(ActionEvent arg0) {
         //     this.jta.select(2, 5);
              this.jta.setCaretPosition(2);
              this.jta.moveCaretPosition(5);
         public static void main(String [] args) {
              BasicFrame bs = new BasicFrame();
              bs.jta.setText("this crap won t work");
    }notice that this solution doesn't work, but if the "select" (or setcaret+movecaret) instruction is put directly in the main, it will work
    Suggestions? Advices? Answers?
    Thanks in advance!

    the code does work, problem is the textArea needs the focus to show the highlighted (selected) text,
    but when you click the button, focus goes to the button.
    run the code then tab (not click) to the textArea, you will see the text selected
    simple fix is to add this line at the end of the constructor
    b.setFocusable(false);

  • JTextArea selection color

    Hi
    I want to be abel to set diffrent colors in a textarea by selecting a
    interval of text och and then selecting a color.
    How is this done?
    I dont mean the selection color, the actual text. The purpose is to have an textarea with lots of news text, and be abel to color mark them for diffrent priority.
    Thanks.

    hi,
    JTextField, JPasswordField, and JTextArea each use a PlainDocument model. PlainDocument allows one font, one color, and is limited to character content. JEditorPane and JTextPane use a StyledDocument model. StyledDocument is much more complex, allowing multiple fonts, colors, embedded images and components, and various sets of hierarchically resolving textual attributes. So either use JEditorPane or JTextPane as per u'r requirement -
    -manoj

Maybe you are looking for

  • OS 10.8.5 Wi-Fi doesn't find "Preferred Network"

    We installed a new modem provided by Comcast that has built in wireless. After naming and establishing the password for the network, I successfully connected via my MacBook Pro, which detected it. Once connected I accessed the "Advanced Settings" scr

  • Send mail only works once in a loop!

    Hi, I'm using the function 'SO_DOCUMENT_SEND_API1' to send an email with a pdf attachment. I'm looping through a list of employees and for each employee sending a mail, this works for the first iteration and runs through the code successfully for the

  • Something very strange is happening with the adjustment brush

    When I brush over an area of a photo with the adjustment brush, LR does not select all of the area I brushed over, regardless how many times I go over it.  The unselected spots look like pepper sprinkled on mashed potatoes, small dots that will not s

  • BUG: DBSequence.equals(Number) != Number.equals(DBSequence)

    Hi, I've noticed that the oracle.jbo.domain.DBSequence (Oracle specific) class' equals method differs in behaviour from the oracle.jbo.domain.Number (Oracle specific) class' equals method. When comparing a DBSequence with a Number (with the exact sam

  • OPRM and authorisation

    Hi All, what is oprm and how to find it in the SQL server 2005 ? I also can't export to ms. excel the authorisation although I login as super user. How to copy authorisation to other database since I failed using copy express ? thanks a lot Rajh