JTextFields inside a JPanel inside a JTable

I have a JTable of one column, in which each row is a JPanel. The JPanel has JTextFields and JComboBoxs. The JPanel implements TableCellRenderer and TableCellEditor. It also declares an attribute as follows;
DefaultCellEditor defCellEd = new DefaultCellEditor(new JComboBox);.
All of the TableCellEditor methods are implemented in the same manner as the following method (except getCellEditorComponent(...)), i.e. they all pass the implementation onto the declared DefaultCellEditor;
public boolean stopCellEditing()
     return defCellEd.stopCellEditing();
getCellEditorComponent(...) is implemented to
return (java.awt.Component)value;
All seems to work fine, with one minor exception. My textfields are right justified, so for text that exceeds the default size of the textfield it is in, the first n characters are not visible initially. I would rather have it left justified with the trailing characters being not visible.
If I do not set the cell editor for the panel (just setting the renderer) the text is left justified - problem there is, none of the fields are editable. Furthermore, testing of the JPanel standalone has the textfields left justified, also.
Any help is appreciated, thanks in advance.

I'm glad that helped.
Basically, every text component has a caret, and the caret wants to be visible all the time, setText() moves the caret to the end, that's why setting the caret to null prevents this behavior.
It appears that Sun doesn't intend to change this behavior so this fix is as far as I know the best we could do for now. See http://developer.java.sun.com/developer/bugParade/bugs/4227520.html for more information.

Similar Messages

  • Setting two JTextFields inside JTable cell

    hi,
    I am really stick trying to figure out how to set two cells inside a JTable cell. This needs to be done because if there is a value already inside the cell then i want to drop another value - this new value should be displayed inside another cell but along with the other value already in the cell.
    I assume that i would need to create two JTextFields.
    But can anyone help me further please.

    That should be a simple issue of customizing table cell editor and renderer.
    See tutorials.

  • Inputverifier+Jtextfield inside JTable

    I've got an application which a JTable.
    Inside the JTable I've got a JTextfield for editing the fisrt column
    jTable1.getColumn("First" ).setCellEditor( new DefaultCellEditor( mytextfield ) );
    The JTextField has a InputVerifier
    This InputVerifier is called when I try to click outside the JTextField
    But The JTextField lost the focus always.
    What should I do to keep the focus on the JtextField ?
    The problem is only when the JTextfield is inside the JTable, if the JTextField is outside then the focus works fine.
    Thanks.
    wmiro.

    Hi,
    Create your own editor which implements TableCellEditor and let the stopCellEditing() method
    have a logic like this:
    public boolean stopCellEditing()
          if (selectedEditor == stringEditor)
             boolean valid = textField.getInputVerifier().verify(textField);
             if (!valid) return false;
          return selectedEditor.stopCellEditing();
       }

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

  • JScrollBar inside a JTable

    I've got a JScrollBar inside a JTable, but the L&F is completely different to other JScrollBars that are not in a table.
    I'm using the WindowsLookAndFeel (through getSystemLookAndFeelClassName()) on Win2k. While progress bars displayed normally have a solid, light-blue bar, the ones in the tables are black and dashed.
    Any clues why it's happening or how to get the in-table bars looking a bit more normal?

    Still puzzled over this one, if anyone has any solutions or wild suggestions, they would be appreciated. ;)

  • How to make textfield appear inside a jtable ????

    hi,
    is there any way that i can make mi textfield show up inside a jtable which i have created ??

    you may have to describe exactly what you are trying to do
    in this thread, you want a textfield for additional values entered
    http://forum.java.sun.com/thread.jspa?threadID=737376&messageID=4234595#4234595
    in this thread, you want the cells uneditable
    http://forum.java.sun.com/thread.jspa?threadID=740286&messageID=4246562#4246562
    and, by the look of the posted code, you want a textfield separate from the table
    here's a simple uneditable table.
    if I click on 'fred', what do you want to happen?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class Testing extends JFrame
      public Testing()
        setLocation(400,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String colNames[] = {"Name", "Age"};
        Object[][] data = {{"joe","21"},{"fred","31"},{"mary","22"}};
        DefaultTableModel dtm = new DefaultTableModel(data,colNames);
        JTable table = new JTable(dtm){
          public boolean isCellEditable(int row,int column){
            return false;}};
        JScrollPane sp = new JScrollPane(table);
        sp.setPreferredSize(new Dimension(300,100));
        getContentPane().add(sp);
        pack();
      public static void main (String[] args){new Testing().setVisible(true);}
    }

  • JTextField in a JPanel

    It's been a couple years since I worked with GridBagLayout. I'm trying to add a JTextField
    to a JPanel but it does not seem to be working - it ignores the GridBagConstraints fill and anchor, changes
    to the JTextField are only visible when resizing the window, and if the text is longer than the
    component it disappears altogether. All I'm trying to do is add some padding around the
    component.
    I'm using 1.6.0u12. Is this related to [this bug|http://bugs.sun.com/view_bug.do?bug_id=4238932]?
    import java.awt.*;
    import javax.swing.*;
    public class Example{
    public static void main(String[] args){
         new Example().start();
    public void start(){
         JTextField tf = new JTextField();
         GridBagLayout gbl = new GridBagLayout();
         GridBagConstraints gbc = new GridBagConstraints();
         gbc.insets = new Insets(7, 7, 7, 7);
         gbc.gridx = 0;
         gbc.gridy = 0;
         gbc.gridwidth = 1;
         gbc.gridheight = 1;
         gbc.fill = GridBagConstraints.BOTH;
         gbc.anchor = GridBagConstraints.EAST;
         JPanel box = new JPanel();
         box.setBackground(Color.YELLOW);
         box.setLayout(gbl);
         box.add(tf, gbc);
         JFrame frame = new JFrame();
         frame.setContentPane(box);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(800, 600);
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
    }

    Apparently x, y, width, height are optional, but the weight is necessary.From the doco
    If all the weights are zero, all the extra space appears between the grids of the cell and the left and right edges.
    There's a gothcha when using weights in a multi column/row GBLayout that's clearly documented but often overlooked: the extra space is distributed in the proportion of the weights. Not the total space. And how the GBLayout treats the weight when gridwidth/height > 1 is anybody's guess, since all that's said is
    The grid bag layout manager calculates the weight of a column to be the maximum weightx of all the components in a column.
    How are you?Same old, same old. Counting down to my retirement next year, [b3]if the posers that be don't raise the retirement age yet again ;-)
    I stop in occasionally, but I see less and less of the people I remember.Yup, we see less and less of TP too :P
    Has everyone jumped ship to another forum?Well, camickr is spreading the Swing joy at about 4 forums nowadays, but I think this is still his 'home' forum. E'hic you may better know as petes1234. Some other regulars have indeed disappeared, most notably BDLH and his MIPs. No news about any of them though.
    Darryl

  • Jtextfield inside jtable..please i need help

    Hello, im trying to put textfield in a cell of Jtable but appears the following text inside of JTextField that i've inserted...
    javax.swing.JTextField[,0,0,0x0,invalid,disabled,layout=javax.swing.plaf.basic.Basic
    TextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.Border
    UIResource$CompoundBorderUIResource@196c1b0,flags=296,maximumSize=,minimumSize
    =,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabled
    TextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=
    javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=
    sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.Color
    UIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontal
    Alignment=LEADING]
    Thus i've implemented a class FBaseTableCellEditor extends DefaultCellEditor that allow me to have JTextfield like cell of JTable.
    this is the source code :
    public class FBaseTableCellEditor extends DefaultCellEditor {
    public FBaseTableCellEditor() {
    super(new javax.swing.JTextField());
    this.editorComponent = new javax.swing.JTextField();
    //this.setClickCountToStart(1);
    ths is the source code to insert a new row in the JTable:
    private void AddRowsinTable(){
    int row = JTable.getRowCount() - 1;
    JTextField[] newrow = CreateRow();
    this.DefaultTableModel.addRow(newrow);
    private JTextField[] CreateRow()
    JTextField[] newrow = {this.JTextField0, this.JTextField1, this.JTextField2, this.JTextField3, this.JTextField4, this.JTextField5, this.JTextField6};
    return newrow;
    PLEASE I NEED HELP...
    Message was edited by:
    negrera

    tripple posting: http://forum.java.sun.com/thread.jspa?threadID=5120228

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • Changing the size of a jbutton inside a jtable

    Hi,
    I have found this example for adding a jbutton to a jtable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=715330
    however, I have cannot seem to figure out how to set the size of the jbutton. Currently, the jbutton is filled to the size of the cell within the jtable, but i want to have it a bit smaller and centered (the rows of my table are rather large in hieght)
    I tried the setSize()
    setPrefferedSize()
    setMinimumSize()
    setMaximumSize()methods, but nothing seems to work. Has anyone been able to do this?

    Use a JPanel instead of a JButton as cell renderer. Put a button inside the panel - use FlowLayout.

  • How to select JLabel inside a JTable

    hi all,
    I have a Jtable which has own renderer so it can store components in it. I have added a Jlabel one of its cells but when I select that row the label stays upon the selected background color. here is a sample screenshot to decribe my problem clearly [http://www.imagecross.com/06/image-hosting-view-01.php?id=6570label.jpg]
    is there any way to select the label inside selected background color.
    - I have already tried to make the label not opaque but it didnt work -
    thanks...

    I have added bold parts of the code below. if you use other components you can make a type casting and do what you want.
    thanks again..
    class ComponentRenderer *extends JComponent*  implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
        *     JLabel l = (JLabel)value;*
        *     if(isSelected) {*
        *          l.setForeground(Color.BLUE);*
        *          l.setOpaque(true);*
        *          l.setBackground(new Color(184, 207, 229));*
        *     else {*
        *          l.setForeground(Color.BLACK);*
        *          l.setOpaque(true);*
        *          l.setBackground(Color.WHITE);*
            return l;
        /*public ComponentRenderer() {
    }

  • My JButton inside a JTable cell does not respond to clicks

    I have a Jtable which extends AbstractTableModel and uses an arraylist to fill the data in the model. The first column of this table is my button column. I have a class for my button coumn which is:
    class MyButtonCol extends AbstractCellEditor
            implements TableCellRenderer, TableCellEditor, ActionListenerMy button column class has getTableCellRendererComponent and getTableCellEditorComponent. My problem is that the button shows on the table but it does not respond to clicks. Any help will be appreciated.

    That does not seem to be the problem. I have the method in my class but it still does not respond to clicks. This is my AbstractTableModel class:
    class WorklisttableModel extends AbstractTableModel{
         protected static List<Worklist> transaction;
         protected String[] columnNames = new String[]{" ", "Modality", "Status","Patient name",
                "Patient ID","Date of birth","Study date","Referring physician","Description"};
         public WorklisttableModel(){
             transaction = new ArrayList<Worklist>();
             fillmodel();
          @Override
          public boolean isCellEditable(int row, int column) {
                return false;
          @Override
          public int getColumnCount() {
                return 9;
          @Override
          public int getRowCount() {
                return (transaction!=null) ? transaction.size() : 0;
          @Override
          public Object getValueAt(int rowIndex, int columnIndex) {
              if(rowIndex < 0 || rowIndex>=getRowCount())
                  return" ";
                  Worklist row = (Worklist)transaction.get(rowIndex);
                  switch(columnIndex){
                      //case 0:return "";
                      case 1:return " "+row.getModality();
                      case 2: return row.getStatus();
                      case 3:return row.getName();
                      case 4:return row.getID();
                      case 5:return row.getDOB();
                      case 6:return row.getStudyDate();
                      case 7:return row.getReferringP();
                      case 8:return row.getDescription();
               return " ";
          public Class getColumnClass(int col){
              return getValueAt(0,col).getClass();
          @Override
          public String getColumnName(int columnIndex) {
                return columnNames[ columnIndex ];
          protected void fillmodel(){
              transaction.add(new Worklist("","US","active","Simpson","1232222",new java.util.Date(73,8,12),new Date(18,8,13),"Dr. Francis","Brain"));
              transaction.add(new Worklist("","US","inactive","Dodggy","3498222",new java.util.Date(83,8,12),new Date(16,8,17),"Dr. Francis","Heart"));
              transaction.add(new Worklist("","CT","active","Williams","7892222",new java.util.Date(98,9,5),new Date(19,2,13),"Dr. Evans","Dental"));
              transaction.add(new Worklist("","MR","inactive","Brian","89765412",new java.util.Date(65,5,23),new Date(19,1,18),"Dr. Evans","Brain"));
              Collections.sort( transaction, new Comparator<Worklist>(){
              public int compare( Worklist a, Worklist b) {
                  return a.getName().compareTo( b.getName() );
    }

  • JCheckBox inside a JTable

    hai,
    i was trying to insert a JCheckBox for one column of the JTable. actually its getting inserted but its not visible. whenever the table is shown, only the value of the check box is visible on that cell, but not the checkbox. only if i click on that corresponding cell, as long as the mouse is pressed, i can view the chk box, but normally only the value is visible.
    can anyone please help me in viewing the check box. please do help i'm breaking my head without knowing the reason for this.
    Thanx u in advance.
    regards,
    Fazlina

    hai,
    thanx for ur quick reply. it does work fine. but now i'm not able to either chk it or unchk it.
    here is my code.can u please help me.
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class TableExample {
    public TableExample() {
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    final String[] names={"FirstCol","SecondCol"};
    final Object[][] data={                                   {"Black",new Boolean(true)},                              {"White",new Boolean(true)}                         };
              // Create a model of the data.
         TableModel dataModel = new AbstractTableModel()
              public int getColumnCount() { return names.length; }
              public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {return data[row][col];}
              public Class getColumnClass(int col)
                   if (col == 1) return Boolean.class;
                   return super.getColumnClass(col);
    // Create the table
    JTable tableView = new JTable(dataModel);
    tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Finish setting up the table.
    JScrollPane scrollpane = new JScrollPane(tableView);
         scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
    scrollpane.setPreferredSize(new Dimension(430, 200));
    frame.getContentPane().add(scrollpane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    new TableExample();
    i donno where i made the mistake can u please help me out as early as possible.
    thanx in advance.
    Regards,
    Fazlina

  • How to display all the files name in same folder inside a JTable?

    Currently i am doing an LAN P2P application (similar to KazAa) which is have a function to search files and list out files name after searched found. I am planning to list all the searched file names in JTable. I am having problem to list the files name on a table field. Can anybodu help : ) ? Please

    I don't understand what your problem is so I'll just refer you to the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables.

  • How to retrieve value from ComboBox inside a Jtable

    Hi everyone, I've this problem: I used the code that I founded to this link:
    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox]
    So I inserted a comboBox in my Jtable but I don't retrieve comboBox's values.
    I tried to retrieve these values in this way:
    myTable1.getModel().getValueAt(rowIndex, columnIndex).getClass();but this code produce a NullPointerException.
    thank you for helping me!!!!

    but I don't retrieve comboBox's valuesCorrect, because the combo box and its data is not part of the TableModel. The TableModel only stores the item that was selected from the combo box when the cell was edited.
    If you are getting an exception it is because you haven't set any data in your table model for the given cell.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

Maybe you are looking for