JSlider 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)
package GUI.TimeView.Component.essai2;
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];
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
        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;
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDialogEditDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new TableDialogEditDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        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:
package GUI.TimeView.Component.essai2;
import 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;
}

Do you need more information?
Was I clear in my question?
Thank you

Similar Messages

  • 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) ?

  • Using JSlider as table component

    Ive been having some problems using JSlider in tables... Ive written several cell editors and renderers but this is the only one that gives me problems. Here is simplified code that i think should work but doesn't:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JSlider;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import java.awt.FlowLayout;
    import java.awt.Component;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    * A main frame with a table in it... wish it had sliders...
    public class TestSliderTable extends JFrame
        /** Creates new TestSliderTable */
        public TestSliderTable()
            addWindowListener(new WindowAdapter()
                public void windowClosing()
                    System.exit(0);
            setUpTable();
        private void setUpTable()
            JTable table = new JTable(new SomeDumbTableModel())
                public TableCellRenderer getCellRenderer(int row, int column)
                    return new JSliderTableCellRenderer();
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.add(table);
            setContentPane(panel);
            pack();
        public static void main(String[] args)
            TestSliderTable frame = new TestSliderTable();
            frame.setVisible(true);
    * A simple cell renderer that should render sliders...
    class JSliderTableCellRenderer extends JSlider
        implements TableCellRenderer
        /** Creates new JSliderTableCellRenderer */
        public JSliderTableCellRenderer()
            super(0, 10, 5);
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                        boolean p3, boolean p4,
                                                        int row, int column)
            int newValue = ((Integer)value).intValue();
            setValue(newValue);
            return this;
    * a simple table model with Integers as values...
    class SomeDumbTableModel extends AbstractTableModel
        public SomeDumbTableModel() { }
        public int getRowCount() { return 10; }
        public int getColumnCount() { return 1; }
        public Object getValueAt(int row, int column) { return new Integer(row); }
    }Anyone have similar problems or know anyway around this?

    Have you tried this:
    http://www.esus.com/javaindex/j2se/jdk1.2/javaxswing/editableatomiccontrols/jtable/jtableslidereditor.html
    Cheers,
    Joris

  • Additional objects in JTable cells

    I would like to place JSlider objects in a JTable, but I am overwhelmed with
    the renderer and editor things. Anyone got any ideas on how to do that?
    I suppose I need to override DefaultCellRenderer and DefaultCellEditor
    constructors.

    Thanks.
    I have looked atthe tutorial, but it focuses on a single object type per cell - I've got two different types (an ImageIcon and a String) that will occupuy a single cell.
    Taking a conceptual leap here, is it possible to create a new TableCellRenderer that houses a JPanel and GridLayout, and then place an ImageIcon and JLabel into that panel? I guess as long as things are JComponents, should I be OK with this approach?
    thanks,
    jpl

  • JSlider as Cell Renderer

    How to add JSlider as table cell renderer? I wrote a custom cell renderer and returning JSlider, but it is not showing up.

    Hi,
    set the follwing as your cell renderer. If you want you can cusomize it according to your requirements.
    class SliderRenderer extends JPanel implements TableCellRenderer
      private JSlider slider = new JSlider();
      public SliderRenderer()
         slider.setOrientation(SwingConstants.HORIZAONTAL);
         silder.setPreferredSize(new Dimension(200,30));
         slider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
         setLayout(new BorderLayout());
         add(slider, BorderLayout.CENTER);
      public Component getTablecellRendererComponent(JTable table, Object value,
                                boolean isSelected, boolean hasFocus,
                                int row, int column)
          slider.setValue(((Integer)value).intValue());
          return this;
    }

  • Tough JSlider TableCellRenderer Problem!

    Hi,
    Ive been doing some work with tables and it involved using alot of different components in them. The only one that i cant get to work is JSlider. Using JSlider as a custom TableCellEditor seems to work fine, but it doesnt see to draw itself as a TableCellRenderer. Below I have some code that seems to illustrate the problem.
    So my question is : has anyone ever used JSlider suceesfully as a TableCellRenderer? If so, got a demonsration or something you had to do? If you have problems too can you think of any way around it (either a hack to get it to work or some other component that looks/works the same)?
    Well I hope this doesnt come down to writing my own JSlider... Anyway, thanks in advance for any help...
    Joshua
    Here is the code. What it does is makes a simple application with a table in it, with integers as values in the center panel. The cell renderer is a panel with a button and a JSlider in it (the slider has a border and the background is set to white to show where is should be). In the bottom panel of the app is the slider panel how it is drawn when it is not in a table.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JSlider;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import java.awt.FlowLayout;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    * A main frame with a table in it... wish it painted sliders in the table
    public class TestSliderTable extends JFrame
        public TestSliderTable()
            addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent evt)
                    System.exit(0);
            setUpTable();
        private void setUpTable()
            JTable table = new JTable(new SomeDumbTableModel())
                public TableCellRenderer getCellRenderer(int row, int column)
                    return new JSliderTableCellRenderer();
            table.setRowHeight(50);
            //make a center panel, with a ScrollPane with the table in it
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            JScrollPane pane = new JScrollPane(table);
            JPanel flowPanel = new JPanel();
            flowPanel.setLayout(new FlowLayout());
            flowPanel.add(pane);
            panel.add(flowPanel, BorderLayout.CENTER);
            //make a panel on the bottom to just show the component
            panel.add(new JSliderTableCellRenderer(), BorderLayout.SOUTH);
            setContentPane(panel);
            pack();
        public static void main(String[] args)
            TestSliderTable frame = new TestSliderTable();
            frame.setVisible(true);
    * A simple cell renderer that should render sliders...
    class JSliderTableCellRenderer extends JPanel
        implements TableCellRenderer
        JSlider slider;
        JButton button;
        /** Creates new JSliderTableCellRenderer */
        public JSliderTableCellRenderer()
            super();
            slider = new JSlider(0, 10, 5);
            slider.setBackground(Color.white); //did this so you can see where the slider should be
            button = new JButton(">>>");
            setLayout(new FlowLayout());
            add(button);
            add(slider);
            add(button);
            slider.setBorder(BorderFactory.createLineBorder(Color.black));
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                        boolean p3, boolean p4,
                                                        int row, int column)
            int newValue = ((Integer)value).intValue();
            slider.setValue(newValue);
            return this;
    * a simple table model with Integers as values...
    class SomeDumbTableModel extends AbstractTableModel
        public SomeDumbTableModel() { }
        public int getRowCount() { return 10; }
        public int getColumnCount() { return 1; }
        public Object getValueAt(int row, int column) { return new Integer(row); }
    }

    I tried adapting this from a JButtonTable example, but gave up.
    http://forum.java.sun.com/thread.jsp?forum=57&thread=121545
    It's got a problem in that the slider doesn't show up until the cell has focus. I was going to set the value field too, but I'm going home to dinner. Good Luck!
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class JButtonTableExample extends JFrame {
      public static void main(String[] args) {
        JButtonTableExample frame = new JButtonTableExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setSize( 400, 100 );
        frame.setVisible(true);
      public JButtonTableExample() {
        super( "JButtonTable Example" );
        DefaultTableModel dm = new DefaultTableModel() {
          public boolean isCellEditable(int rowIndex, int columnIndex) {
         if (columnIndex == 1) return false;
         return true;
        dm.setDataVector(new Object[][]{{"x","1"},
         {"y","2"}},
         new Object[]{"Slider","Value"});
        JTable table = new JTable(dm);
    //    editor.addCellEditorListener(new MyListener(table, 1, "Side A", "Side B"));
        table.getColumn("Slider").setCellRenderer(new SliderRenderer());
        SliderEditor seditor = new SliderEditor(50);
        table.getColumn("Slider").setCellEditor(seditor);
        getContentPane().add(new JScrollPane(table));
      class SliderRenderer extends JSlider implements TableCellRenderer {
        public SliderRenderer() {
          this.setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value,
           boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
          } else{
         setForeground(table.getForeground());
         setBackground(UIManager.getColor("Button.background"));
    //      this.setText( (getValue()==null) ? "" : getValue.toString() );
          return this;
      class SliderEditor extends DefaultCellEditor {
        protected JSlider slider;
        public SliderEditor(int Value) {
          super(new JCheckBox());
          slider = new JSlider();
          slider.setOpaque(true);
          slider.setValue(Value);
    //      slider.addActionListener(new ActionListener() {
    //     public void actionPerformed(ActionEvent e) {
    //       fireEditingStopped();
        public Component getTableCellEditorComponent(JTable table, Object value,
           boolean isSelected, int row, int column) {
          if (isSelected) {
         slider.setForeground(table.getSelectionForeground());
         slider.setBackground(table.getSelectionBackground());
          } else{
         slider.setForeground(table.getForeground());
         slider.setBackground(table.getBackground());
          return slider;
        public Object getCellEditorValue() {
          return new Integer(slider.getValue());
        public boolean stopCellEditing() {
          return super.stopCellEditing();
        protected void fireEditingStopped() {
          super.fireEditingStopped();
    }

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • How to select a specific cell in a JTable?

    Hi there,
    in a JTable, I would like to select a specific cell (to highlight it) from a JButton.
    Here a sample code...
    Who could help me to fill it?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableSelection{
        public static void main (String args[]) {
          JFrame frame = new MyFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
    class MyFrame extends JFrame{
      public MyFrame(){
        setTitle("TableSelection");
        setSize(WIDTH,HEIGHT);
        DefaultTableModel myModel = new DefaultTableModel(2,2);
        JTable myTable = new JTable(myModel);
        myTable.setCellSelectionEnabled(true);
        JButton button00 = new JButton("select 0,0");
        button00.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (0,0)");
         //--- what code is required to select the cell(0,0)?
        JButton button11 = new JButton("select 1,1");
        button11.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (1,1)");
         //--- what code is required to select the cell(1,1)?
        Box myBox = new Box(BoxLayout.Y_AXIS);
        myBox.add(new JScrollPane(myTable));
        myBox.add(button00);
        myBox.add(button11);
        getContentPane().add(myBox, BorderLayout.CENTER);
      private static final int WIDTH=200;
      private static final int HEIGHT=200;
    }Thanks a lot for your help.
    Denis

    Use the addColumnSelectionInterval(int index1, int index2)method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addColumnSelectionInterval(int,%20int)
    and the addRowSelectionInterval(int index1, int index2) method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addRowSelectionInterval(int,%20int)
    Hope that helped.
    afotoglidis

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              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();
    }

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

  • Refresh data in a jtable when data changes

    I have a jtable grdTable and a tableModel mytableModel which extend abstract table model
    I have a jcheckbox in the column 1 which i want to uncheck all
    I am doing the following.The data is changed ,I could see by doing susyem.out.println() but the data in the table does not refreshes.
    public void showTablechanges()
    TableModel tm = grdTable.getModel;
    for(int i=0 ;i<grdTable.getRowCount();i++)
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ( (MyTableModel)tm).fireTableDataChanged();
    grdTable.repaint();
    What am i missing or what wrong I am doing.How can i make the data refresh.
    I tried do a sys out after seting the value and it is showing as false but the checkbox is still checked.I have tried a lot of things but I am not able to refresh the jtable.
    Please please help.
    Thanks

    Thanks so much for the reply I read the links.I modified my code as
    public void showTablechanges() {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    TableModel tm = grdTable.getModel;
    for (int i = 0; i < grdTable.getRowCount(); i++) {
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ((MyTableModel) tm).fireTableDataChanged();
    grdTable.repaint();
    This makes no difference.What strange thing is happening out of 12 checkboxes ,11 are unchecked but the first one always remains checked.EVen without the
    invoke later 11 are unchecked and 1 remains checked
    This method is in a panel and this panel is invoked from another MAin panel which has a changelistener for this panel.
    i.e if the method above is in myPanel.java then in my main panel,I have
    myPanel.addChangeListener(this)
    Also if i remove the line
    ((MyTableModel) tm).fireTableDataChanged();
    All checkboxes remains checked.
    I am really confused and this looks very tough to me ,Can you find out what is wrong
    Thanks,

Maybe you are looking for

  • Do I have to purchase another program to be able to hear sound on my movies

    Hi, I just got my new video ipod yesterday and I am trying to download all my old videos onto it. I downloaded the proper iTunes and transferd all my videos into there, then I tried the right click and "convert selection to ipod" button and it took 3

  • Changing the compression mode..

    So I have a slideshow I'd like to export to DVD. The pictures that are animated to get the ken burns effect. I watched it on an LCD tv on a dvd player and the interlaced fields were so prevelant that the movie was almost unwatchable. In FCE4, at 100%

  • Itunes closes itself without updating my ipod.

    It started happening yesterday, its never happened before, and as far as i know, i'm the only person its happened to. whenever i connect my ipod to my computer, it waits about 30 seconds doing nothing and then a window pops up that says "itunes has e

  • Multiple iTunes XML Files?

    Hello everyone. I have a problem. I want to move my iTunes library over to my external hard drive. DO NOT post a link on how to do this. I have read all of them. The problem is that I have multiple iTunes XML files. Not just one. I don't know what to

  • How do I make photos in Bridge open to PSE 6 by default?

    I have both PSE 4 and PSE 6 on my computer...Just bought the version 6. When I double click a photo in Bridge it opens in PSE 4. How do I make PSE 6 the default opener for Bridge? MAC OSX.5.7