Combobox Renderer in JTable

Can someone please post code showing me how to make a renderer that would indicate a combobox in a JTable? I already have the combobox editor there, but I want the renderer to show a small down arrow, indicating to the user that the cell is a combobox.
Thanks!

public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
    public ComboBoxRenderer(Vector items) {
        super(items);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
        if (isSelected && !hasFocus){
            setBackground(table.getSelectionBackground());
            setForeground(table.getSelectionForeground());
        }else{
            setBackground(table.getBackground());
            setForeground(table.getForeground());
        setSelectedItem(value);
        return this;
[/code[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Help required for creating Row Renderer for JTable

    Hi all,
    I am trying to create customize row renderer for JTable.
    My requirements are as below.
    |-----------------|-------------------|------------------|------------------|-------|----------------|
    |Category | Product ID |Description | Unit Price |Qty | Sub-Total |
    |-----------------|-------------------|------------------|------------------|-------|----------------|
    I have designed a combobox for category and product ID columns inside JTable. I want to put a listener on Category ID such that product IDs in selected categories will be visible in product ID drop down of selected row keeping other rows unchanged.
    Column renderer is defining a class for entire column but by setting that im getting same values in all the rows for product IDs. And if I update values for one product ID dropdown, entire column data is changing.
    Even im not able to put array of combobox for product ID column as number of rows are not fixed and increasing runtime.
    Can anyone suggest me how can i customize Cells under particular column with JComboBox?
    Regards,
    Mahesh Kedari
    Fidus Technologies Ltd.
    Edited by: m1JustM1 on Feb 8, 2010 4:48 AM

    Start by reading [this |http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender] tutorial. If you still have questions afterward, feel free to post an SSCCE .

  • ComboBox size in JTable

    How do you set the size of a combobox inside a JTable cell. I have used setPreferredWidth but the ccombo box is still huge. I have done searches and not found any answers.
    Thanks

    I've always let the UI take care of it. I don't set the minimum, maximum or preferred sizes and the UI sets the size to the size fo the cell.

  • Align for multi-header renderer in JTable

    Hi,
    I have a question about multi-header renderer in JTable. Here is the problem, please help me:
    I used the MultiLineHeaderRenderer class example from
    http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html
    This example makes the header to be centered (as setHorizontalAlignment(JLabel.CENTER)). Also, it is for the all the headers with 2 lines (i don't know how to describe it).
    In my project, I have just a few header with 2 lines, most of them are one line. By using this example renderer class, I have the header height is bigger, of course because of some 2 lines headers, and one line header is automatically set as the TOP. What I want is to make one line header to be set as the BOTTOM just like in EXCEL.
    Please help me, sorry for my technical explaination (poor huh?)
    Thanks in advance.

    If I understand correctly just put a space then a new line before your text for your cell that you want the text at the bottom.
    like this: " \nBottom Text"
    You'll need the leading space because of how StringTokenizer works.

  • Refreshing renderer in jtable

    hi all,
    i am using JLabel for rendering a JTable, but the problem is
    JTable is not refreshing properly.
    import java.awt.Component;
    import java.awt.Container;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class SampleTable extends JFrame
        public SampleTable()
            Container container = getContentPane();
            container.add(getHtmlTable());
            setSize(400, 400);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        private JScrollPane getHtmlTable()
            Object[] tblColHeaders = {"a","b"};
            Object[][] tradedata = {
                    {"<HTML><table >"
                     + "<tr><td >row 1, cell 1</td></tr></table></HTML>", "<HTML><table>"
                           + "<tr><td>row 1, cell 1</td></tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                           + "</table></HTML>"},
                    { "<HTML><table >"
                     + "<tr><td >row 1, cell 1</td></tr>"
                     + "</table></HTML>", "<HTML><table>"
                           + "<tr><td>row 1, cell 1</td></tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                           + "</table></HTML>"},
                    { "<HTML><table >"
                     + "<tr><td >row 1, cell 1</td></tr>"
                     + "</table></HTML>", "<HTML><table>"
                           + "<tr><td>row 1, cell 1</td>/tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                           + "</table></HTML>"}};
            JTable table = new JTable(tradedata,tblColHeaders){
                public boolean isCellEditable(int row,int col){
                    return false;
            table.setDefaultRenderer(Object.class,new MyTableCellRenderer());
            JScrollPane scrTabel = new JScrollPane(table);
            return scrTabel;
        public class MyTableCellRenderer extends JLabel implements TableCellRenderer
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus,
                                                           int rowIndex, int vColIndex)
                setText(value.toString());
                setSize(table.getColumnModel().getColumn(vColIndex).getWidth(),
                        getPreferredSize().height);
                if (table.getRowHeight(rowIndex) != getPreferredSize().height)
                    table.setRowHeight(rowIndex, getPreferredSize().height);
                if(isSelected){
                    setBackground(table.getSelectionBackground());
                    setForeground(table.getSelectionForeground());
                return this;
        public static void main(String[] args)
            new SampleTable();
    }thanks
    daya

    1) Your renderer is in an infinite loop because column one need a row height of 16, so you change the height, but column two need a row height of 48, so you change the height.
    But whenever you change the row height the table needs to render the entire row, so it tries to render column 1 again and it resets the height, then column 2 and it resets the height etc, etc.
    2) All you want you renderer to do is change the height, so don't create the renderer from scratch. That is don't extend JLabel, extend DefaultTableCellRenderer so you don't need to add all the custom code.
    Your renderer should be something like this:
        public class MyTableCellRenderer extends DefaultTableCellRenderer
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus,
                                                           int rowIndex, int vColIndex)
                super.getTableCellRendererComponent(table,
                    value, isSelected, hasFocus, rowIndex, vColIndex);
                if (table.getRowHeight(rowIndex) < getPreferredSize().height)
                    table.setRowHeight(rowIndex, getPreferredSize().height);
                return this;
        }

  • Please help! How to add a combobox on a jtable

    Hi, I have seen on google and here many codes to add a combobox in a jtable but none of them seem to work, I need the urgently.
    My problem is that I must add a comboBox or a JComboBox to a cell inside a JTable on a predefined column. It means that on the column 2 I must add diferent comboboxes for eac row. How can I do it, please help.

    The celleditor is the component shown and the cellrenderer is the first render of a component in the cell and dont have to be the same jcombo box?
    The code on ther post does this:?
    returning a diferent combobox for all the cells on the column depending on the row selected, but as long as only one cell can be selected at a time it seems to hace different jcomboboxes added a time?
    Is there anyway to render any combobox with different values, my program must let the user chose the teacher it want to teach a definen subject, so the combo must have the teacher of a subject loaded on a database, the combos are not constants. I guess I can manage to use the way you showed me, but is there anyway to render a combo just by adding it to a cell! maybe doing changes to the tablemodel or things like that?

  • 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.

  • COMBOBOX & CHECKBOX RENDERER IN JTABLE

    Hi,
    I created JXTable by using swingx palette in Netbeans IDE. In two columns of my table, for each row I want to put checkboxes and comboboxes. I searched the ways on internet and I finalise my code. However, because I used cell editor, I just see my checkboxes and comboboxes when I enter a specific cell. I read all tutorials but unfortunately I cannot learn how to use renderer to show comboboxes and checkboxes all the time. In below you could check my code and if possible please teach how to use renderers and try to give feedback to my code by fixing it. Thank you.
    *(P.S Please don't send any web site for tutorial, i searched almost all of them; but I can't understand the logic of it.)*
    // SET UP THE COMBO BOX
    public void setUpOverwriteValueColumn(JXTable table, TableColumn overwriteValCol) {
    valueCombo = new JComboBox();
    Field field = new Field();
    ArrayList values = new ArrayList();
    values = field.getValues();
    for(String a:values){
    valueCombo.addItem(a);
    overwriteValCol.setCellEditor(new DefaultCellEditor(valueCombo));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    overwriteValCol.setCellRenderer(renderer);
    // SET UP THE CHECK BOX
    public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
    valueChk = new JCheckBox();
    overwriteCol.setCellEditor(new DefaultCellEditor(valueChk));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for check box");
    overwriteCol.setCellRenderer(renderer);
    setUpOverwriteColumn(monitorTable, monitorTable.getColumnModel().getColumn(3)); //add checkbox to 3rd column
    setUpOverwriteValueColumn(monitorTable, monitorTable.getColumnModel().getColumn(4)); //add combobox to 4th column

    Finally I can add renderers. But, now I have different question. When user clicks on the checkbox I want to enable the combo box. I mean if user clicks the checkbox in row 3; only the combo box which placed in row 3 should be enabled; other combos in other rows should not be enabled. Please help if you know the answer. Here is my code:
    public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
        public ComboBoxRenderer(Vector items) {
            super(items);
            setOpaque(false);
        public Component getTableCellRendererComponent(
                                                    JTable table,
                                                    Object value,
                                                    boolean isSelected,
                                                    boolean hasFocus,
                                                    int row,
                                                    int column){
            if (isSelected && !hasFocus){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            }else{
                setBackground(table.getBackground());
                setForeground(table.getForeground());
              setSelectedItem(value);
            return this;
    public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer
      public CheckBoxRenderer() {
        setOpaque(false);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
      public Component getTableCellRendererComponent(
                                                        JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
        if (value != null) {
          this.setSelected( ( (Boolean) value).booleanValue());
        return this;
    }To show:
    public void setUpOverwriteValueColumn(JXTable table,
                                     TableColumn overwriteValCol) {
            Vector v = new Vector();
            Field field = new Field();
                ArrayList <String> values = new ArrayList<String>();
                values = field.getValues();
                for(String a:values){
                    v.addElement(a);
                ComboBoxRenderer renderer = new ComboBoxRenderer(v);
                overwriteValCol.setCellRenderer(renderer);
        // SET UP THE CHECK BOX
        public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
                CheckBoxRenderer renderer = new CheckBoxRenderer();
                overwriteCol.setCellRenderer(renderer);
        }Edited by: duygu_simsek on Jun 18, 2009 11:27 AM

  • Need combobox with a Jtable to view client & server files

    Hellow Everybody,
    I am quite new to Java, although I have experience with other
    programming languages.
    I have searched for tutorials, code, examples etc. but have not found
    much that can help me so far. I am a BCA student & I am appearing for my last year exams. I studied about various Java programs in my course and I decided to make a Swing based FTP Server. Although I not expert in Java , but I have learnt the network programming very much clearly, and that�s why by the help these I wrote a program but it not complete. I have given the program below.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.StringTokenizer;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.EmptyBorder;
    import sun.net.TelnetInputStream;
    import sun.net.ftp.FtpClient;
    public class Client extends JFrame {
    public static int BUFFER_SIZE = 10240;
    protected JTextField userNameTextField = new JTextField("anonymous");
    protected JPasswordField passwordTextField = new JPasswordField(10);
    protected JTextField urlTextField = new JTextField(20);
    protected JTextField fileTextField = new JTextField(10);
    protected JTextArea monitorTextArea = new JTextArea(5, 20);
    protected JProgressBar m_progress = new JProgressBar();
    protected JButton putButton = new JButton("Upload <<");
    protected JButton getButton;
    protected JButton fileButton = new JButton("File");
    protected JButton closeButton = new JButton("Close");
    protected JFileChooser fileChooser = new JFileChooser();
    protected FtpClient ftpClient;
    protected String localFileName;
    protected String remoteFileName;
    public Client() {
    super("FTP Client");
    JPanel p = new JPanel();
    p.setBorder(new EmptyBorder(5, 5, 5, 5));
    p.add(new JLabel("User name:"));
    p.add(userNameTextField);
    p.add(new JLabel("Password:"));
    p.add(passwordTextField);
    p.add(new JLabel("URL:"));
    p.add(urlTextField);
    p.add(new JLabel("File:"));
    p.add(fileTextField);
    monitorTextArea.setEditable(false);
    JScrollPane ps = new JScrollPane(monitorTextArea);
    p.add(ps);
    m_progress.setStringPainted(true);
    m_progress.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.white,
    Color.gray));
    m_progress.setMinimum(0);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(m_progress, BorderLayout.CENTER);
    p.add(p1);
    ActionListener lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread uploader = new Thread() {
    public void run() {
    putFile();
    disconnect();
    uploader.start();
    putButton.addActionListener(lst);
    putButton.setMnemonic('U');
    p.add(putButton);
    getButton = new JButton("Download >>");
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread downloader = new Thread() {
    public void run() {
    getFile();
    disconnect();
    downloader.start();
    getButton.addActionListener(lst);
    getButton.setMnemonic('D');
    p.add(getButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (fileChooser.showSaveDialog(Client.this) != JFileChooser.APPROVE_OPTION)
    return;
    File f = fileChooser.getSelectedFile();
    fileTextField.setText(f.getPath());
    fileButton.addActionListener(lst);
    fileButton.setMnemonic('f');
    p.add(fileButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (ftpClient != null)
    disconnect();
    else
    System.exit(0);
    closeButton.addActionListener(lst);
    closeButton.setDefaultCapable(true);
    closeButton.setMnemonic('g');
    p.add(closeButton);
    getContentPane().add(p, BorderLayout.CENTER);
    fileChooser.setCurrentDirectory(new File("."));
    fileChooser
    .setApproveButtonToolTipText("Select file for upload/download");
    WindowListener wndCloser = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    disconnect();
    System.exit(0);
    addWindowListener(wndCloser);
    setSize(720, 240);
    setVisible(true);
    public void setButtonStates(boolean state) {
    putButton.setEnabled(state);
    getButton.setEnabled(state);
    fileButton.setEnabled(state);
    protected boolean connect() {
    monitorTextArea.setText("");
    setButtonStates(false);
    closeButton.setText("Cancel");
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    String user = userNameTextField.getText();
    if (user.length() == 0) {
    setMessage("Please enter user name");
    setButtonStates(true);
    return false;
    String password = new String(passwordTextField.getPassword());
    String sUrl = urlTextField.getText();
    if (sUrl.length() == 0) {
    setMessage("Please enter URL");
    setButtonStates(true);
    return false;
    localFileName = fileTextField.getText();
    // Parse URL
    int index = sUrl.indexOf("//");
    if (index >= 0)
    sUrl = sUrl.substring(index + 2);
    index = sUrl.indexOf("/");
    String host = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    String sDir = "";
    index = sUrl.lastIndexOf("/");
    if (index >= 0) {
    sDir = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    remoteFileName = sUrl;
    try {
    setMessage("Connecting to host " + host);
    ftpClient = new FtpClient(host);
    ftpClient.login(user, password);
    setMessage("User " + user + " login OK");
    setMessage(ftpClient.welcomeMsg);
    ftpClient.cd(sDir);
    setMessage("Directory: " + sDir);
    ftpClient.binary();
    return true;
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    setButtonStates(true);
    return false;
    protected void disconnect() {
    if (ftpClient != null) {
    try {
    ftpClient.closeServer();
    } catch (IOException ex) {
    ftpClient = null;
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(0);
    putButton.setEnabled(true);
    getButton.setEnabled(true);
    fileButton.setEnabled(true);
    closeButton.setText("Close");
    Client.this.setCursor(Cursor
    .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    SwingUtilities.invokeLater(runner);
    protected void getFile() {
    if (localFileName.length() == 0) {
    localFileName = remoteFileName;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    fileTextField.setText(localFileName);
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    int size = getFileSize(ftpClient, remoteFileName);
    if (size > 0) {
    setMessage("File " + remoteFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    } else
    setMessage("File " + remoteFileName + ": size unknown");
    FileOutputStream out = new FileOutputStream(localFileName);
    InputStream in = ftpClient.get(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    if (size > 0) {
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    } else {
    int kb = counter / 1024;
    setProgressString(kb + " KB");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void putFile() {
    if (localFileName.length() == 0) {
    setMessage("Please enter file name");
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    File f = new File(localFileName);
    int size = (int) f.length();
    setMessage("File " + localFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    FileInputStream in = new FileInputStream(localFileName);
    OutputStream out = ftpClient.put(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void setMessage(final String str) {
    if (str != null) {
    Runnable runner = new Runnable() {
    public void run() {
    monitorTextArea.append(str + '\n');
    monitorTextArea.repaint();
    SwingUtilities.invokeLater(runner);
    protected void setProgressValue(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressMaximum(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setMaximum(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressString(final String string) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setString(string);
    SwingUtilities.invokeLater(runner);
    public static int getFileSize(FtpClient client, String fileName)
    throws IOException {
    TelnetInputStream lst = client.list();
    String str = "";
    fileName = fileName.toLowerCase();
    while (true) {
    int c = lst.read();
    char ch = (char) c;
    if (c < 0 || ch == '\n') {
    str = str.toLowerCase();
    if (str.indexOf(fileName) >= 0) {
    StringTokenizer tk = new StringTokenizer(str);
    int index = 0;
    while (tk.hasMoreTokens()) {
    String token = tk.nextToken();
    if (index == 4)
    try {
    return Integer.parseInt(token);
    } catch (NumberFormatException ex) {
    return -1;
    index++;
    str = "";
    if (c <= 0)
    break;
    str += ch;
    return -1;
    public static void main(String argv[]) {
    new Client();
    The above given code is not yet complete. I want some specific features to be implemented in this code that is given below.
    1.     A login Gridlayout or Borderlayout & within it the username & password textfield.
    2.     When the username and password will request to server and if it will success then the textfields of the username & password have to be disable.
    3 . Two Combobox. One will give client directories and files and another
    will give the server directories and files.
    4 . Below the Combobox two JTable will be given & the tables wll show the
    client and server directories and files.
    Could anybody give me the codes that I want. If anybody check this code please help me????
    With Regards,
    DILLU

    Well Mr Michael_Dunn,
    Thanks for responding my query. First of all I would like to tell that
    this FTP server is going to be my project and that's why I am submmiting my question. I told in my points that I want a Jcombobox & a JTable for displaying that files & directories. whenever I set the directories in the combobox the files will be displayed in the JTable
    I hope you understand my point

  • Editable Combobox in a JTable

    Hi All,
    I have a editable combobox in a normal JTable as one of columns.Can any body help me to set the size to the entered text in editable combobox. Means if I set the length to 5 then it should accpet only 5 characters.so how to achive it ??
    Regards
    Suresh

    First get cell editor that should be a combobox. Then get its editor that should be text box and then set its size.

  • JSlider renderer in JTable

    Hi,
    I insert JSlider in a column of a JTable, redefining renderer and editor. The problem is that when I resized the size of the JTable (or the column with the sliders), the sliders are not resized. They are only resized if I move another window over them. Is is a repaint I have to apply ? The problem is that I do not know where to apply it.
    This is my code: I put only the JTable and the renderer, not the editor and the other components.
    This is the JTable (with a main to launch it)
    import GUI.TimeView.CategoryTimeDimensionView;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TableDialogEditDemo extends JPanel {
        private boolean DEBUG = false;
        JTable table;
        public TableDialogEditDemo() {
            super(new GridLayout(1,0));
            table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(200, 48));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
            table.getColumnModel().getColumn(0).setResizable(false);
            table.getColumnModel().getColumn(0).setPreferredWidth(80);
            table.getColumnModel().getColumn(1).setResizable(false);
            table.getColumnModel().getColumn(1).setPreferredWidth(80);
            table.getColumnModel().getColumn(2).setCellRenderer(new SliderRenderer());
            table.getTableHeader().setReorderingAllowed(false);
            //Add the scroll pane to this panel.
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"Curve", "Color", "Transparency", "Displayed"};
            private Object[][] data = {
                {"Average", Color.black, 70, new Boolean(false)},
                {"Minimum", Color.black, 70, new Boolean(false)},
                {"Maximum", Color.black, 70, new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                            + " to " + value
                            + " (an instance of "
                            + value.getClass() + ")");
                data[row][col] = value;
                fireTableCellUpdated(row, col);
                if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
            private void printDebugData() {
                int numRows = getRowCount();
                int numCols = getColumnCount();
                for (int i=0; i < numRows; i++) {
                    System.out.print("    row " + i + ":");
                    for (int j=0; j < numCols; j++) {
                        System.out.print("  " + data[i][j]);
                    System.out.println();
                System.out.println("--------------------------");
            private Object[] longValues;
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFra
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }and the renderer:
    mport java.awt.Color;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import java.awt.Component;
    import javax.swing.BorderFactory;
    import javax.swing.JSlider;
    import javax.swing.border.Border;
    public class SliderRenderer extends JSlider implements TableCellRenderer {
        Border unselectedBorder = null;
        Border selectedBorder = null;
        public SliderRenderer() {
            setMinimum(0);
            setMaximum(100);
            setBackground(Color.white);
            setBounds(0, 0, 100, 10);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object val, boolean isSelected, boolean hasFocus, int row, int column) {
                if (isSelected) {
                    if (selectedBorder == null) {
                        selectedBorder = BorderFactory.createMatteBorder(1,3,1,3, table.getSelectionBackground());
                    setBorder(selectedBorder);
                } else {
                    if (unselectedBorder == null) {
                        unselectedBorder = BorderFactory.createMatteBorder(1,3,1,3, table.getBackground());
                    setBorder(unselectedBorder);
            int value = (Integer) val;
            setValue(value);
            return this;
    }Thank you for your answers.

    Thank you for your answers,
    blackbug wrote:
    why did you assign a default position and size for your slider.
    try to remove the default size. or the setBounds property.It was something I forgot. I removed it, but it does not change anything.
    Olek wrote:
    Try to use revalidate() or validate() with the sliders after resizing the panel.I had to the table the listener:
    addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentResized(java.awt.event.ComponentEvent evt) {
                 //table.getColumnModel().getColumn(2).getCellRenderer().getTableCellRendererComponent(table, 70, false, false, 0, 2).validate();
            });but I do not know how to apply the validate() methode: how can I find the slider?
    With table.getColumnModel().getColumn(2).getCellRenderer().getTableCellRendererComponent(table, 70, false, false, 0, 2) ?

  • JFormattedTextField as custom cell renderer in JTable?

    I have my custom renderers in my custom JTable that work quite good so far. After upgrading to JDK 1.4, i want to finally use formatted text fields in my JTable. So, i extended my renderes to also support formatters. But this doesn't seem to work. The formatter of my DateRenderer's constructor is used. When i try to change it via my JTable's custom method
         * Set formatter for a column. The formatter is only used if a corresponding renderer is set up (see configColumn()).
         * @param columnIndex Index of colum (0 = first column).
         * @param formatter Formatter to set.
         * @return TableColumn object for given index or null.
        public TableColumn setFormatter(int columnIndex, AbstractFormatter formatter) {
            TableColumn result = null;
            if (columnIndex >= 0 && columnIndex < getColumnCount()) {
                result = getColumnModel().getColumn(columnIndex);
                TableCellRenderer tcr = result.getCellRenderer();
                if (tcr instanceof DateRenderer) {
                    DateRenderer dr = (DateRenderer) tcr;
    System.out.println("setFormatter("+columnIndex+","+formatter+")...");
                    dr.setFormatter(formatter);
                }//else: todo
            }//else: columnIndex invalid
            return result;
        }//setFormatter()that has a different formatter, it is not changed!

    Instead of using setFormatter(), i wrote my own set method:
         * Set DateFormat.
         * @param format DateFormat to set.
        public void setFormat(DateFormat format) {
            setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(format)));
        }//setFormat()

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

  • Custom Cell Renderer and JTable

    Hello all,
    here is what i am trying to do. i want that when a user clicks on a cell the
    color of the cell should change to say red. when the user clicks on the other
    cell the red color in the first cell should remain.
    the way i am trying do to this is by making an object which contains an on and
    off state. based on click ie valuechanged() method in table
    based on the row and column i change the value of the boolean state on. my
    custom cell renderer checks whether the state is on or off
    and then changes the color.
    rightnow I am able to change the color on click but am unable to retain the
    color. so how can i retain the color.
    // making table
              vectorForSingleRow.add(0, "");                    
              vectorForSingleRow.add(1, new CellColorObject(TEXT_EDITOR));     
              Vector tempVectorForSingleRow = new Vector(vectorForSingleRow);               
              tempVectorForSingleRow.set(0, name);     
              vectorForSingleRow.set(1, new CellColorObject(TEXT_EDITOR));          
              data.add( tempVectorForSingleRow ); // data is a vector
              myTableModel = new DefaultTableModel(data, columnNames)
              //Customrenderer
              public Component getTableCellRendererComponent(JTable table, Object value,      
                                                     boolean isSelected, boolean hasFocus, int row, int column) {
              CellColorObject myObj = (CellColorObject)value;
              this.setText(value.toString());
                   System.out.println("value.getClickedStatus() " + myObj.getClickedState());
                   if(myObj.getClickedState()){
                        System.out.println("in 2");     
                        this.setBackground(Color.PINK);
                   if(isSelected){
                   System.out.println("in 1");
                   this.setSelected(true);
    // other things and end of method
    //custom object for storing state of the cell                                   
    public class CellColorObject{
         private String name = "";
         private boolean clickedState = false;
         public CellColorObject(String incomingName){
              name = incomingName;
         public void setClickedState(boolean newClickedState){
         System.out.println("setClickedState");
              clickedState = newClickedState;
         public boolean getClickedState(){
         System.out.println("getClickedState()");
              return clickedState;
         public String toString(){
              return name;
    // valueChanged method
           public void valueChanged(ListSelectionEvent e) {
             if (e.getValueIsAdjusting()) return;
              if(column == 1){
                   CellColorObject tempObj = (CellColorObject) myTable.getValueAt(row,column);
                   tempObj.setClickedState(true);
                   myTable.setValueAt(tempObj, row, column);
    // other things and method end
              

    You problem is that you are NOT setting the clickedState of your object:
    public Component getTableCellRendererComponent(JTable table, Object value,                                                       boolean isSelected, boolean hasFocus, int row, int column) {                         CellColorObject myObj = (CellColorObject)value;          this.setText(value.toString());                         System.out.println("value.getClickedStatus() " + myObj.getClickedState());               if(myObj.getClickedState()){                    System.out.println("in 2");                         this.setBackground(Color.PINK);               }               if(isSelected){               System.out.println("in 1");               this.setSelected(true);In the above, you have
    if (myObject.getClickedState())
    /// do code..
    notice you have:
    if (isSelected)
    this.setSelected(true);
    Maybe I am missing something, but I see no code that sets your objects clicked state when selected. My guess is that you should be doing value.setClickedState(true) when the thing is selected, something like:
    CellColorObject myObj = (CellColorObject)value;
    if (isSelected)
    myObj.setClickedState(true);
    else
    myObj.setClickedState(false);
    BUT, you didn't finish your code snippet within the method there, so perhaps you do this already?
    What you have should almost work, in that every single cell will call this method and if the object's clickedState is true, it should set the background color. Just make sure you are setting the objects clicked state.

  • Losing comboBox selection in JTable

    I have a JTable where one column consists of comboBoxes. It is possible to add and remove rows from this table using the associated buttons.
    Unfortunately if I have made a choice from a comboBox, yet not selected another cell in the table, then I use the 'add' button to add a new row, I lose the selection just made in the comboBox.
    If I first select another cell in the table this is not a problem and it works fine.
    Any help much appreciated....

    thanks for that, but I'm afraid it was no help.
    I'm using Java 1.1.7 and the getCellEditor(int, int) method doesn't exist. doing the same with getCellEditor() doesn't produce the required results.
    The comboBoxModel is updated when a new selection is made, but the cellEditor isn't updated until you click on another location in the table. Unfortunately I don't know how it goes about doing this, so I can't imitate it in my 'add' method

Maybe you are looking for