Multiple scrollable JTextArea in a JTable

Hi,
I want to created a JPanel and added a Jtable (10 columns and 10 rows). So I've 100 JTextArea in a panel. But i don't know how to make all these textareas scrollable. Can anyone help me?
thanks,
Yigit

Your message does sound rather confusing. In any case, this is how you add a scrollpane to a JTextArea, tweak it a bit and add it to a pane:
    listTextArea = new JTextArea();
    listTextArea.setFont(new Font("Verdana", Font.PLAIN, 14));
    listTextArea.setEditable(false);
    listTextArea.setLineWrap(true);
    listTextArea.setWrapStyleWord(true);
    JScrollPane listTextScrollPane = new JScrollPane(listTextArea);
    listTextScrollPane.setVerticalScrollBarPolicy(JScrollPane.
                                                  VERTICAL_SCROLLBAR_AS_NEEDED);
    listTextScrollPane.setHorizontalScrollBarPolicy(JScrollPane.
        HORIZONTAL_SCROLLBAR_NEVER);
    listTextScrollPane.setPreferredSize(new Dimension(860, 340));
    listPanel.add(listTextScrollPane);You can do a similar operation on a JTable. What I am trying to understand is if you would like to be able to add a scrollpane to each cell or something similar...

Similar Messages

  • Trouble updating a JtextArea from a JTable ListSelectionListener..

    Hi, I'm having trouble updating a JtextArea from a JTable ListSelectionListener, it is working for another JTextArea but I have created JNMTextArea which extends JTextArea and I am getting no data passed to it.
    Any help is really greatly appreciated. Im a relative newbie to Java.
    Here is the class declaration for JNMTextArea
    public class JNMTextArea extends JTextArea
         //Constructor
         public JNMTextArea(String text){
              super(text);
              setLineWrap(true);
              setEditable(false);
         //Constructor
         public JNMTextArea()
              this(new String());
         //This sets the data in setText, works ok.
         void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    Here is where I use JNMTextArea, Im
    class JNMGui extends JFrame implements ActionListener, WindowListener{
         public static JNMTextArea txtPktContent;
         //Constructor
              JNMGui(){
                   buildGUI();
         private void buildGUI(){
         mainWindow = new JFrame("Monitor");
         tblPacket = new JTable(tblPacketM);
         tblPacket.setToolTipText("Packet Panel");
         tblPacket.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         if (ALLOW_ROW_SELECTION) {
              ListSelectionModel rowSM = tblPacket.getSelectionModel();
              rowSM.addListSelectionListener(new ListSelectionListener() {                     public void valueChanged(ListSelectionEvent e) {
                        if (e.getValueIsAdjusting())
                             return;
                        ListSelectionModel lsm =      (ListSelectionModel)e.getSource();
                        if (lsm.isSelectionEmpty()) {
                             System.out.println("No rows are selected.");
                        else {
                             int selectedRow = lsm.getMinSelectionIndex();
                             selectedRow++;
                             String str;// = "";
                             //Unsure if I need to create this here!
                             txtPktContent = new JNMTextArea();
                             //This works perfectly
                             txtPktType.append ( "Packet No: " + Integer.toString(selectedRow) + "\n\n");
                             Packet pkt = new Packet();
                             pkt = (Packet) CaptureEngine.packets.elementAt(selectedRow);
                             if(pkt.datalink!=null && pkt.datalink instanceof EthernetPacket){
                                  str = "Ethernet ";
                                  //THis works txtPktType is another JTextArea!!          
                                  txtPktType.append ( s );
                                  //This is not working
                                  //I realise displayPacket return type is void but how do get
                                  //the setText it created to append to the JNMTextArea??               
                                  txtPktContent.displayPacket(pkt);
              //Adding to ScrollPane
              tblPane = new JScrollPane(tblPacket);
              txtPktTypePane = new JScrollPane ( txtPktType );
              txtPktTypePane.setToolTipText("Packet Type");
              txtPktContentPane = new JScrollPane ( txtPktContent );
              txtPktContentPane.setToolTipText("Packet Payload");
              panel.add( tblPane, BorderLayout.CENTER );
    //End Class JNMGui

    void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    This seems really odd. Notice that you pass in "p" but use "buffer". Where is "buffer" defined?

  • Help reqd. in Scrollable JTextArea

    Simple JTextarea query.. how to create Scrollable JTextArea.
    Thanks.

    Thanks. I did it like this. When I am appending the text , Text area width is getting expanded but scroll bar is not coming. How to fix the width & height of a scroll bar & getting scroll bar if text is more. Also How to go for a new line in text area.
    JTextArea textArea = new JTextArea(5,10);
    JScrollPane scroll = new JScrollPane(textArea);
    textArea.append("TEST j jnkejfemvlemf l mcelfmle ekmlemvl vkemv");
    jPanel.add(textArea);
    thanks in advance.

  • Swing Problem : Wrap Multiple line in a Cell (JTable)

    Hello...
    I'm doing a swing app. The functions included are to print the Jtable...
    in Colum 3 i've applied wrapping word in a cell.. the problem is when i print the table, the border in column 3 which wrap the word will not be visible...y?how can i solve this problem...can see my code like below
    MyCellRenderer cellRenderer = new MyCellRenderer(); 
    TableColumn column = null;
      column = tblProgram.getColumn(ResourceBundle.getBundle("Program").getString("TBL_DESC"));
    //get data in column 3  
    column.setCellRenderer(cellRenderer);
      public class MyCellRenderer extends JTextArea implements TableCellRenderer {
            public MyCellRenderer() {
              setLineWrap(true);
              setWrapStyleWord(true);
              setMargin(new Insets(0, 5, 0, 5));
          public Component getTableCellRendererComponent(JTable table, Object
                  value, boolean isSelected, boolean hasFocus, int row, int column) {
               setText((String)value);
              setSize(table.getColumnModel().getColumn(column).getWidth(),
                      getPreferredSize().height);
              if (table.getRowHeight(row) != getPreferredSize().height) {
                      table.setRowHeight(row, getPreferredSize().height);
              return this;
       } ty in advance :D

    Multi-Post:
    http://forum.java.sun.com/thread.jspa?threadID=741629&tstart=20
    Thanks for fixing the code format tags, next time just edit the post instead of reposting.

  • Multiple Cell Selection in a JTable (again...)

    Hi All -
    I'm trying to get a JTable working well with the ability to select multiple cells in the way you'd expect to be able to (in Excel for example). By this I mean, hold down ctrl to add to a selection, hold shift to select between the last selection and the new one, be able to drag multiple regions with the mouse and have them be selected.
    I've seen lots of talk about this, for example on this thread:
    http://forum.java.sun.com/thread.jspa?threadID=619580&start=0&tstart=0
    (the code here will not work in the 'general' case, for example it doesn't really support dynamic table resizing)
    ...and found some pretty extensive code from here:
    http://www.codeguru.com/java/articles/663.shtml
    ...that kinda half works. (but the selection model is very strange once you get it running. Not at all what the average user would be used to)
    Does anyone have this working 100% with code they can share? It is very surprising to me that this is not the default behavior in Swing to be honest.
    I'm sure that I can come up with a solution for my situation, but I may as well not waste the time if someone already has something working for this.
    Thanks!

    If you have columnSelectionAllowed,rowselectionAllowed and cellSelectionEnabled then you can select cell by cell if you use the control key,
    Now the problem is, if you don't have input by your keyboard, in my case, I have a big table and I need to select diferent cells that match a certain criteria,
    jTable2.setRowSelectionInterval(j,j); //but this only works not for different rows 5 - 120 - 595
    I'm trying to use:
    jTable2.changeSelection()
    but still don't have good results....
    If any one could help to this matter will be really appreciated...
    thanks...

  • Multiple selection of checkbox  in  jtable

    hi
    I am using jtable in which first coloumn is using checbox.Ihave used celleditor and cell renderer for that.I want to check multiple checboxes
    at a time and on click of update button wanto send that information to database.But i m not able to check multiple checkboxes.As sson as i click on 2nd checkbox prwvious selection get cleared.Please help me as soon as possible.

    .Ihave used celleditor and cell renderer for that.I want to check multiple checboxesThere is no need to use custom renderers or editors, they are provided by the JTable.
    Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables" for a working example.

  • Tab transversal while using JTextArea as a JTable cell editor..

    I'm working on a project that will use a JTable with a JTextArea cell editor to create a chart for classroom scheduling. Searching on Google, I found a way to use a JTextArea as a cell editor and render the cell properly. However, when editing a cell, pressing the Tab key inserts a tab, rather than leaving the cell and going to the next one, as happens with just a regular JTable. In fact, none of the keyboard shortcuts that work on a JTable work once the JTextArea cell editor is used. Does anyone know of any way to resolve this? Below is some code I'm using to create a sample GUI, just to verify that I can do this. Another question is would it be easier to use a bunch of JLabels and JTextAreas, remove the padding from those JTextAreas, and try to allow for Tab transversals between stand-alone JTextAreas, rather than JTextAreas as JTable cell editors?
    Thanks!
    package edu.elon.table;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GUI
         private JFrame frame;
         private String[] columnNames = {"Classroom", "8:00-9:10", "9:25-10:35",
              "10:50-12:00", "12:15-1:25", "1:40-2:50", "1:40-3:20 (MW)",
              "3:35-5:15 (MW)", "5:30-7:10 (MW)"};
         private Object[][] data = {columnNames,
              {"ALAM 201 (42)\nENG 110 LAB", "", "", "", "", "", "", "", ""},
              {"ALAM 202 (42)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 203 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 205 (40)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 206 (39)\nSINK, TV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 207 (40+)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 214 (38)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 215 (42)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 216 (42)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 301 (40)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 302 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 304 (35)\nFRENCH", "", "", "", "", "", "", "", ""},
              {"ALAM 314 (30)\nDP, PSY, COMPUTER ASSISTED", "", "", "", "", "", "",
              {"ALAM 315 (40)\nPC LAB, DP/DVD", "", "", "", "", "", "", "", ""}};
         private JTable table;
         public GUI()
              frame = new JFrame();
              table = new JTable(data, columnNames);
              table.setRowHeight(table.getRowHeight()*2);
              TableColumnModel cModel = table.getColumnModel();
              TextAreaRenderer renderer = new TextAreaRenderer();
              TextAreaEditor editor = new TextAreaEditor();
              for (int i = 0; i < cModel.getColumnCount(); i++)
                   cModel.getColumn(i).setCellRenderer(renderer);
                   cModel.getColumn(i).setCellEditor(editor);
              frame.setLayout(new GridLayout(1,0));
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
    public static void main (String[] args)
    GUI gui = new gui();
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaRenderer extends JTextArea
    implements TableCellRenderer {
    private final DefaultTableCellRenderer adaptee =
    new DefaultTableCellRenderer();
    /** map from table to map of rows to map of column heights */
    private final Map cellSizes = new HashMap();
    public TextAreaRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    public Component getTableCellRendererComponent(//
    JTable table, Object obj, boolean isSelected,
    boolean hasFocus, int row, int column) {
    // set the colours, etc. using the standard for that platform
    adaptee.getTableCellRendererComponent(table, obj,
    isSelected, hasFocus, row, column);
    setForeground(adaptee.getForeground());
    setBackground(adaptee.getBackground());
    setBorder(adaptee.getBorder());
    setFont(adaptee.getFont());
    setText(adaptee.getText());
    // This line was very important to get it working with JDK1.4
    TableColumnModel columnModel = table.getColumnModel();
    setSize(columnModel.getColumn(column).getWidth(), 100000);
    int height_wanted = (int) getPreferredSize().getHeight();
    addSize(table, row, column, height_wanted);
    height_wanted = findTotalMaximumRowSize(table, row);
    if (height_wanted != table.getRowHeight(row)) {
    table.setRowHeight(row, height_wanted);
    return this;
    private void addSize(JTable table, int row, int column,
    int height) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) {
    cellSizes.put(table, rows = new HashMap());
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) {
    rows.put(new Integer(row), rowheights = new HashMap());
    rowheights.put(new Integer(column), new Integer(height));
    * Look through all columns and get the renderer. If it is
    * also a TextAreaRenderer, we look at the maximum height in
    * its hash table for this row.
    private int findTotalMaximumRowSize(JTable table, int row) {
    int maximum_height = 0;
    Enumeration columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
    TableColumn tc = (TableColumn) columns.nextElement();
    TableCellRenderer cellRenderer = tc.getCellRenderer();
    if (cellRenderer instanceof TextAreaRenderer) {
    TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
    maximum_height = Math.max(maximum_height,
    tar.findMaximumRowSize(table, row));
    return maximum_height;
    private int findMaximumRowSize(JTable table, int row) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) return 0;
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) return 0;
    int maximum_height = 0;
    for (Iterator it = rowheights.entrySet().iterator();
    it.hasNext();) {
    Map.Entry entry = (Map.Entry) it.next();
    int cellHeight = ((Integer) entry.getValue()).intValue();
    maximum_height = Math.max(maximum_height, cellHeight);
    return maximum_height;
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaEditor extends DefaultCellEditor
    public TextAreaEditor() {
         super(new JTextField());
    final JTextArea textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(null);
    editorComponent = scrollPane;
    delegate = new DefaultCellEditor.EditorDelegate() {
    public void setValue(Object value)
    textArea.setText((value != null) ? value.toString() : "");
    public Object getCellEditorValue()
    return textArea.getText();
    }

    Using the KeyEvent manager and playing around with the JTextArea, I was able to get a JTable using JTextAreas as the cell editors that worked very close to the way the regular JTable works. You have to hit Tab twice to shift focus to another cell, or hit Tab once and then an arrow key. Also, Alt-Enter will allow you to enter a cell for editing. All of the changes were made to the TextAreaEditor class, which should now read as follows:
    class TextAreaEditor extends DefaultCellEditor implements KeyListener
         private int lastKeyCode;
         public TextAreaEditor(final JTable table) {
              super(new JTextField());
              lastKeyCode = KeyEvent.CTRL_DOWN_MASK;
              final JTextArea textArea = new JTextArea();
              textArea.setWrapStyleWord(true);
              textArea.setLineWrap(true);
              textArea.addKeyListener(this);
              textArea.setFocusable(true);
              textArea.setFocusAccelerator((char) KeyEvent.VK_ENTER);
              JScrollPane scrollPane = new JScrollPane(textArea);
              scrollPane.setBorder(null);
              scrollPane.setFocusable(false);
              editorComponent = scrollPane;
              delegate = new DefaultCellEditor.EditorDelegate() {
                   public void setValue(Object value) {
                        textArea.setText((value != null) ? value.toString() : "");
                   public Object getCellEditorValue() {
                        return textArea.getText();
         public void keyTyped(KeyEvent ke)
              // TODO Auto-generated method stub
         public void keyPressed(KeyEvent ke)
              if (ke.getKeyCode() == KeyEvent.VK_TAB)
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusNextComponent();
                   return;
              if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.isShiftDown())
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusPreviousComponent();
                   return;
              if ((lastKeyCode == KeyEvent.CTRL_DOWN_MASK) &&
                        (ke.getKeyCode() == KeyEvent.VK_ENTER))
                   ke.consume();
                   editorComponent.requestFocus();
              else
                   lastKeyCode = ke.getKeyCode();
         public void keyReleased(KeyEvent ke)
              // TODO Auto-generated method stub
         }

  • Scrollable JTextArea problem. Tried the techniques of previous posts.

    Hi guys,
    I know this is a very common post on this forum. I have tried the solutions mentioned in previos posts, but somehow I am unable to make a JTextArea Scrollable.
    I have written the following code :
              TAlab1 = new JTextArea(temp);
              TAlab1.setBounds(50, 130, 530, 50);
              TAlab1.setBorder(BorderFactory.createEtchedBorder() );
              TAlab1.setLineWrap(true);
              TAlab1.setEditable(false);
              jsp = new JScrollPane(TAlab1);
              p.add(jsp); // where p is JPanelHere, if I add jsp, then the JTextArea is not visible. If I add TAlab1, then I get a JTextArea, but which is not scrollable.
    I would appreciate any of your assistance.
    Regards
    kbhatia

    Calling setBounds can get you in trouble. Hardcoding values is almost always a bad idea. Here's a short demo of adding a JTextArea to a JScrollPane;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ScrollTest extends JFrame{
        private String longString = "This is just a long string to be added over and over again to textarea\n";
        int times = 0;
        private JTextArea textArea;
        public ScrollTest() {
            buildGUI();
        private void buildGUI(){
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            JPanel centerPanel = buildCenterPanel();
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            JPanel buttonPanel = buildButtonPanel();
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        private JPanel buildButtonPanel() {
            JPanel retPanel = new JPanel();
            JButton addButton  = new JButton("Add Text");
            addButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    addText();
            retPanel.add(addButton);
            return retPanel;
        private void addText() {
            textArea.append(times+ " "+longString);
            times +=1;
        private JPanel buildCenterPanel() {
            JPanel retPanel = new JPanel(new GridLayout(1,0, 5,5));
            textArea = new JTextArea(5,10);
            textArea.setWrapStyleWord(true);
            textArea.setLineWrap(true);
            textArea.setEditable(false);
            textArea.setEnabled(false);
            JScrollPane jsp = new JScrollPane(textArea);
            retPanel.add(jsp);
            return retPanel;
        public static void main(String[] args) {
            new ScrollTest();
    }Cheers
    DB

  • Multiple Line cell render in  JTable

    The issue here is that what's the right way to judge
    how many lines is needed to show the Object value in TableCellRender's
    public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    The way by FontMetrics or by Component's getPreferredSize() is not correct.
    For a short Object value = "FAC Question" for which the table column is wide enough to display whole string,
    the width by calculating FontMetrice on this Object could be larger than the width of table column.
    For example:
    Object value = "FAC Question A";
    tableColumn.getPreferredSize().width = 75;
    fontMetrics.stringWidth(value)=120;
    getTableCellRenderComponent(...).getPreferredSize().width=120

    Hi, use
    JTable table = new JTable();
    DefaultListSelectionModel  dlm =  new DefaultListSelectionModel();
    dlm.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION  ); //1( the first one should be the one you are looking for)
    or (choose 1 or 2, the rest stays the same)
    dlm.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );//2
    table.getColumnModel().setSelectionModel(dlm);
    table.setCellSelectionEnabled(true);Hope this helps.
    Greetings Michael.

  • Scrollable JTextArea

    I am having serious issues with a JTextArea and a JScrollPane. The code is posted below but I'll say what I am trying to do. I am creating a game and am creating a chat form. I have a JTextArea where all the chat will be displayed and then right below it a JTextField that accepts user input. The chat functions correctly, but doesn't display properly. There are two issues that I need addressed. One, the chat doesn't properly flow, what it does it shows 4 lines, then the rest disappears. Two, the scrollbar shows up, but does not scroll, it does not react to user input at all, the mouse wheel doesnt work, I can't click on the arrows, nor can I drag the scrollbar.
    I have does this successfully in several applications and I am either faced with a java bug, an inconvenience, and am just plain overlooking something stupid. Thanks for the help.
    Below is the code I use to setup my interface. mappanel is a custom control, it extends JPanel, rightpanel is another custom control, the postedchat is a JTextArea, the rest I believe is self explainatory.
    this.setLayout(null);
              Rectangle bounds = this.getContentPane().getBounds();
              mappanel = new MapPanel(this);
              mappanel.setBounds(0, 0, mappanel.getWidth(), mappanel.getHeight());
              this.add(mappanel);
              rightpanel = new RightPanel();
              rightpanel.setBounds(mappanel.getWidth() + 1, 0, rightpanel.getHeight(), rightpanel.getWidth());
              this.add(rightpanel);
              postedchat = new JTextArea();
              //postedchat.setSize(100, 50);
              //postedchat.setEditable(false);
              //postedchat.setBounds(0, 0, mappanel.getWidth(), (int)bounds.getHeight() - mappanel.getHeight() - 20);
              JScrollPane scrollarea = new JScrollPane(postedchat);
              //scrollarea.getViewport().add(postedchat);
              scrollarea.setBounds(0, mappanel.getHeight() + 1, mappanel.getWidth(), (int)bounds.getHeight() - mappanel.getHeight() - 20);
              scrollarea.setPreferredSize(new Dimension(mappanel.getWidth(), (int)bounds.getHeight() - mappanel.getHeight() - 20));
              this.add(scrollarea);
              //Chat field KeyListener
              final JTextField chat = new JTextField();
              chat.setBounds(0, (int)bounds.getHeight() - 20, mappanel.getWidth(), 20);
              class SendChat implements KeyListener
                   public void keyPressed(KeyEvent e)
                        if(e.getKeyCode() == KeyEvent.VK_ENTER)
                             String message = chat.getText();
                             server.SendChat(message);
                             chat.setText("");
                   public void keyTyped(KeyEvent e){}
                   public void keyReleased(KeyEvent e){}
              chat.addKeyListener(new SendChat());
              this.add(chat);
              this.repaint();Thank you for all the help.

    I do not want to use a layout manager as I wish to place them based on x, y coordinates.Most newbies want to do this because they don't understand the power of layout managers. Learning how to use layout managers will save you time in the long run and you will have a better more maintainable GUI.
    Unless there is another way to place the components EXACTLY where I want them.Its called using a layout manager. Rarely do you ever need to specify exact pixel locations of a component. You only want components to be line up in a straight line relative to other components so the GUI looks neat and tidy.
    Is the JScrollPane not working because of the lack of a LayoutManager? Sometimes it can be the problem. But you didn't post a SSCCE so we don't know for sure.
    Also, you should not be using a KeyListener on your text field. You should be using an ActionListener. The text field will invoke the ActionListener when enter is pressed on the text field.
    I suggest you read the Swing tutorial for proper usage of layout managers and other other Swing features.

  • How to create a cell column with JTextArea in JTable

    I am developing an Application using Java Swings. I need to use JTextArea in my JTable. I need the code to do so. I also want to show the scrollbars in the JTextArea.
    Any efforts in this regard would be of great help. Thanks in advance.
    Thanks
    Alagu

    have a look at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=134412

  • Problem : Not able to select multiple checkboxes in the JTable

    Here i am trying to select the multiple check boxes in the jtable. But i am not able to do that. I set the jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); also.
    Can any one help on this...

    [email protected] wrote:
    Here i am trying to select the multiple check boxes in the jtable. But i am not able to do that. I set the jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); also.
    Can any one help on this...That's row selection, not check boxes. The normal way to have active checkboxes in a JTable is with an editable Boolean column. The effect of clicking such a checkbox is to cause the table to call setValueAt() in the data model with a Boolean object value, and it's up to the data model to deal with that change.

  • Multiple selection in JTable

    Hi ,
    The problem is to select multiple rows and columns in the JTable like that of a excel application and have the focus on the first column of the last row. for example if select cells from ( 1,1 ) to ( 4,4), after selection the focus should be in cell (4,1). i have written a prgram( which is below) which uses listSelection to find out the cells which are selected. i found out the cells which are selected also. but i do not know how to get the focus on that cell. i have attached the code below also.. i want to know whether there is any method which set the focus to the particular cell. Can the problem above can be solved in any other way..or a simpler way..
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class myTable {
    public static void main(String a[] ) {
              JFrame myframe = new JFrame();
              JTable jtable = new JTable(10,10);
              jtable.setCellSelectionEnabled(true);
         // add the listener to the table
    ListSelectionModel listSelectionModel;
         OSSTableSelectionHandler obj = new OSSTableSelectionHandler(jtable,10,10);
         listSelectionModel = jtable.getSelectionModel();
    listSelectionModel.addListSelectionListener(obj);
         myframe.getContentPane().add(jtable);
         myframe.show();
    } // end of public static void main
    } // end of class of myTable
    class OSSTableSelectionHandler implements ListSelectionListener {
                   JTable table;
         int row;
                   int col;
    OSSTableSelectionHandler(JTable tab, int r, int c ) {
         table = tab;
    row = r;
              col = c;
    public void valueChanged(ListSelectionEvent e) {
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                   int i = 0,j = 0;
    int firstIndex = e.getFirstIndex();
    int lastIndex = e.getLastIndex();
    boolean isAdjusting = e.getValueIsAdjusting();
    if (lsm.isSelectionEmpty()) {
    System.out.println(" Selection empty ");
    } else {
    // Find out which indexes are selected.
                        int maxrow = 0 ;
    int minIndex = lsm.getMinSelectionIndex();
    int maxIndex = lsm.getMaxSelectionIndex();
    for ( i = minIndex; i <= maxIndex; i++) {
    if (lsm.isSelectedIndex(i)) {
                                  if ( maxrow < i )
                                       maxrow = i;
                                  for (j = 0;j < col ;j++ )
                                       if ( table.isCellSelected(i,j) )
                                            System.out.println("The selected index is " + i + " " + j);
                             } // end of if                    
    } // end of for
                   // after this maxrow contains the last row that has beeb selected
                   // this for loop is to find out the first column in the maxrow that is selected
                   for (j = 0;j < col ;j ++ )
                        if ( table.isCellSelected(maxrow,j) )
                                  break;
                   // set the focus to the column ( maxrow, j )
    } // end of else
    } // end of fucn value changed
    } // end of class OSSTableSelectionHandler

    Whic cell is focused depends on where you begin your selection. The cell that you press your mouse first will be the focused one. Here is how I implement the mutiple selection functionality in a JTable as what MS Excel provides. This class is independent of my any other package. your table has to have column headers and a upper left JLabel corner(int the scroll pane containing the table) in order to make this class which I named TableSelectionAdapter function properly. You can revise and imporve it as you need, however.
    package petrochina.riped.gui.table.tableadapter;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.datatransfer.*;
    import java.util.*;
    * Enables multiple selection funtionality on <code>JTable</code>s.
    * @author Guanglin Du,SEC of Riped, PetroChina,
    * [email protected]
    * @version 1.0 2002/09/16
    public class TableSelectionAdapter extends MouseAdapter {
    private String newline = "\n";
    private boolean DEBUG = false;
    // private boolean DEBUG = true;
    private JTable myTable = null;
    private boolean shiftKeyDown = false;
    private boolean ctrlKeyDown = false;
    private int firstSelectedColIndex = -1;
    * Constructs with a <code>myTable</code> to simplify its reusability.
    * Guanglin Du, 2002/09/19
    * @param myTable     a <code>JTable</code>
    public TableSelectionAdapter(JTable myTable) {      
    this.myTable = myTable;
    initTableSelection();
    * The initTableSelection method: initializes the row/column/cell
    * selection functionality of the table.
    * Guanglin Du, 2002/09/19
    public void initTableSelection() {      
    getMyTable().setSelectionMode(
              ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
         //Cell selection
         myTable.addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
              myTable.setColumnSelectionAllowed(true);
              myTable.setRowSelectionAllowed(true);
         setMyKeyListener(); //shift/control key listener
         //column selection functionality
         JTableHeader myTableHeader = getMyTable().getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
         //enalbles select-all functionality
         setSelectAllFunction();
    * This setSelectAllFunction isto set the select-all functionality
    * when the upper left corner label of the JTable is clicked.
    * Note: JTable's parent JScrollPane has to be found.
    * Guanglin Du, 2002/09/19
    public void setSelectAllFunction() {      
    Container firstParent = getMyTable().getParent();
    if (firstParent instanceof JViewport) {
         Container secondParent = firstParent.getParent();
         if (secondParent instanceof JScrollPane) {
         JScrollPane myScrollPane = (JScrollPane)secondParent;
         JLabel myLabel =
              (JLabel)myScrollPane.getCorner(JScrollPane.UPPER_LEFT_CORNER );
         myLabel.addMouseListener(this);
    * Detects shift/control key state.
    * DGL, 2002/09/18
    public void setMyKeyListener() {
         getMyTable().addKeyListener(new KeyAdapter(){               
         //keyPressed
         public void keyPressed(KeyEvent e){
              //shift key state
              if(e.isShiftDown())     shiftKeyDown = true;                    
              //control key state
              if(e.isControlDown()) ctrlKeyDown = true;
    //keyReleased
         public void keyReleased(KeyEvent e){
              //shift key state
              if( !e.isShiftDown() ) shiftKeyDown = false;                    
              //control key state
              if( !e.isControlDown() ) ctrlKeyDown = false;
    * Adds the table header listener to enable single/multiple column selection.
    * DGL, 2002/09/17
    public void setTableHeaderListener() {
         JTableHeader myTableHeader = myTable.getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
    * Returns the <code>myTable</code> property value.
    * @return myTable the table that this class handles
    public JTable getMyTable() {
    return myTable;
    * Sets <code>myTable</code> property value of this class.
    * @param myTable the table that this class handles
    public void setJTable(JTable myTable) {
         this.myTable = myTable;
    * Returns the shiftKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getShiftKeyDown(){
         return shiftKeyDown;
    * Return the ctrlKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getCtrlKeyDown(){
         return ctrlKeyDown;
    * This inner class handles the column selection, the same
    * behavior as MS Excel.
    * Guanglin Du, 2002/09/18
    class TableHeaderListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {    
         stopLatestCellEditing(); //To save the data being edited
         if(DEBUG) System.out.print("mousePressed on ");
         JTableHeader myColumnHeader = (JTableHeader)e.getSource();
         Point myPoint = e.getPoint();
         int selectedColIndex = myColumnHeader.columnAtPoint(myPoint);
         if(DEBUG) System.out.print("the header of column "
              + selectedColIndex+newline);
         JTable table = myColumnHeader.getTable();
         //The following column selection methods work only if these
         //properties are set this way
         table.setColumnSelectionAllowed(true);
         table.setRowSelectionAllowed(false);
         int myRowCount = table.getRowCount();
         //makes this table focused, so that setMyKeyListener method can
         //listen for shift/control KeyEvent
         table.requestFocus();
    //     System.out.println("myRowCount = " + myRowCount);
         if( getShiftKeyDown() ){
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(firstSelectedColIndex > -1) {
              table.addColumnSelectionInterval(firstSelectedColIndex, selectedColIndex);
              firstSelectedColIndex = -1;//restore to -1
         } else if( getCtrlKeyDown() ) {
         table.addRowSelectionInterval(0,myRowCount-1);
         table.addColumnSelectionInterval(selectedColIndex,selectedColIndex);
         } else {
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(DEBUG) System.out.println("shiftKeyDown = " + shiftKeyDown
              +";"+" ctrlKeyDown = " + ctrlKeyDown);     
         //saves the first selected column index
         firstSelectedColIndex = selectedColIndex;
    * MouseAdapter implemenation.
    * mousePressed: sets the select-all functionality
    * when upper left corner label of the table is clicked
    * Guanglin Du, 2002/09/18
    public void mousePressed(MouseEvent e) {    
         if(DEBUG) System.out.println("Select all");
         stopLatestCellEditing();//To save the data in editing
         getMyTable().selectAll();
    * Triggers the latest <code>ActionEvent</code> in a table cell to save
    * the latest data. Or, the newly input data will not be stored into the table
    * model and cannot be retrieved.
    public void stopLatestCellEditing() {
    int editingRow = getMyTable().getEditingRow();
    int editingCol = getMyTable().getEditingColumn();
    if (editingRow != -1 && editingCol != -1){
         TableCellEditor cellEditor =
         getMyTable().getCellEditor(editingRow, editingCol);
         cellEditor.stopCellEditing();
    Here is how you can use it in your coding(where myTable is a JTable instance you create):
         /* Adds TableSelectionAdapter to enable all kinds of selection action. */
         TableSelectionAdapter tableSelect = new TableSelectionAdapter(myTable);     

  • Multiple selection in JTable for deletion

    Dears,
    I'm using Jdeveloper 9.0.3.3 on 8.1.7 Oracle DB.
    I noticed that when a JTable is bound to a View object ==> only one row can be selected.
    My situation -which I think is very common- I have a screen with JTable where I can edit a row and commit my updates or select multiple selection in JTable and delete them at once ; thats what I need.
    It is very like the test of any application module but allow multiple selection and deletion in JTable for user's selected rows.
    How this could be done in JClient?
    Thankx in advance.

    Thanks for your suggestions! They both would work as workarounds, I think. I tried another way:
    Following code changes a TableBinding bound JTable's selection model to Multi select (thanks to Shailesh!!).
    void setMultiSelectionModel(JTable tbl)
    class MultiSelectionListListener implements javax.swing.event.ListSelectionListener
    ListSelectionModel defSelModel;
    MultiSelectionListListener(ListSelectionModel model)
    defSelModel = model;
    public void valueChanged(javax.swing.event.ListSelectionEvent e)
    if (!e.getValueIsAdjusting())
    ListSelectionModel listModel = (ListSelectionModel)e.getSource();
    int leadIndex = listModel.getLeadSelectionIndex();
    if (leadIndex == listModel.getAnchorSelectionIndex()
    && leadIndex == listModel.getMaxSelectionIndex()
    && leadIndex == listModel.getMinSelectionIndex())
    //change currency on the bound iterator only if
    //one row is being selected.
    defSelModel.setSelectionInterval(leadIndex, leadIndex);
    ListSelectionModel newModel = new DefaultListSelectionModel();
    newModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    newModel.addListSelectionListener(new MultiSelectionListListener(tbl.getSelectionModel()));
    tbl.setSelectionModel(newModel);
    This fixes the bug if you select some rows and then select a row before the first selected one. Seems to work great.

  • Urgent need of your help for multiple JTables Print from a single JPanel

    I need your help to print multiple table content from JPanel
    JTables are generated dynamically in a JPanel or JPanels. I need to take print as it is in JPanel

    Alternatively you could write a simple class to print JTables with a series of calls to paintString( myString), and various calls to fillRect(...) tfor asthetics. It is quite simple. I currently use such a class that I wrote in under 200 lines of code that has a very professional look, and the print jobs are less than half the size of printing the JTable directly.
    The idea being that it takes a JTable as a parameter ( and maybe other params to control color, style, font, etc... ). It would have one primary method, print() which actually handles the printing, It may also uses other methods to control the look of the application.
    A problem I have faced with printing a JTable directly is ensuring that the botom row on each page and the top row on every page after the first one lines up correctly. After a while it was simply easier, and more customizable, to write my own print class.
    AC

Maybe you are looking for

  • Custom Number Format Default to Numeric Keyboard

    Hello, I recently put together a timesheet form for our superintendents.  I have some fields to accept our company's 6-digit cost codes.  Initially, I used the general  Number format.  This worked well since, on the iPad, the numeric keyboard came up

  • Updating Acrobat 9 MAC

    I have about 50 Macs on 10.7 I need to update from 9.3 to 9.5.1. I have updated my mac. I copied my Acrobat through Apple Remote Desktop. Under the user (non administrator) it does not show it changed. I log the user out and login as the local admini

  • Need To Download Original Purchase Again of A Business Card App.

    I recently purchased Business Card Composer 5 by BeLight Software through my Apple app store. Everytime I try to create a business card, I get a *watermark* on my design and an annoying box that asks me whether I wish to purchase the app. This happen

  • Enquiry on Skype For Business

    Hi There, I'm Dan here. I would like to enquire regarding skype for business. Is it possible for my company to use skype as our company staff communication for messaging purposes only.(e.g Office Comunicator) And is it possible if we assign our IT st

  • Track iPhone based on data usage

    Is there any way to see where an iPhone last connected to the internet? My iPhone was stolen and I'm trying to find it. I can see the data usage on my AT&T account after the time of the theft, is there a way to find where it connected at?