JTable in JPanel

Super(wo)man,
Is it possible to put a JTable into a JPanel without loss
of the column headers? Is it possible to reply with an example since you already must have tried to fix this problem.

Hi! :)
Yes it is possible and easy. Just put your table in a JScrollPane. Something like that:
JTable table = new JTable (new MyTableModel ()); // assuming you already have a table model..
JPanel panel = new JPanel (new BorderLayout ());
panel.add (new JScrollPane (table), BorderLayout.CENTER);That's all.. :)
CUL8er,
Nick.

Similar Messages

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • JTable in JPanel last Column resize clips JTable doesnt repaint JPanel

    I have a JTable in a JPanel, when I drag the last column of the JTableHeader (u can see the column resizing as the text of the Table HeaderColumn moves with the drag) the JTable is outside the JPanel. Only when u click on another component and then click back on the JTableHeader does it repaint.
    I have tried jPanel.revalidate(); in the mouseDragged event of MouseMotionListener on the JTableHeader and all manner or repaints and fireTableStructureChanged. But I dont understand the order of events.
    The last bug to fix!!!
    NB I dont want to use scrollpane as its not necessary and as many tables are synchronized with one table it makes repaints less smooth
    Thanks Paul

    Well, I didn't find an answer but I did find a solution.
    The JPanel is the problem. I use it to help with layout which is not obvious in this example.
    As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
    If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
    So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
    I would still like to know why?
    ////////KBS
    JTabbedPane myTP = new JTabbedPane();
    Box myOne = Box.createHorizontalBox();
    Box myTwo = Box.createHorizontalBox();
    myOne.add(pane);
    myTP.add("One", myOne);
    myTP.add("Two", myTwo);
    ////////KBS

  • JTable in JPanel in JTabbedPane in JScrollPane in JSplitPane problem

    I have a JSplitPane with a divider in the center; of which the top is a JPanel and the bottom is a JScrollPane that contains a JTabbedPane, for which each tab contains a JPanel which contains a JTable.
    When I move the divider up, so that it now takes up 75% of the JSplitPane, the JScrollPane and the JTabbedPane expand with the JSplitPane, but the JPanel that contains the JTable remains the same size that it had at the beginning.
    What I would like to see is more rows of the JTable as I move the divider to give the JScrollPane more room.
    Is there an easy way to keep all of the J components sizes in sync as the JSplitPane gets larger or smaller ? (JDK 1.3.1)

    Hi,
    The JPanels which you have inside each tab of the JTabbedPanes should have BorderLayout and the JScrollPanes which hold the JTables should be added with the BorderLayout.CENTER constraint. This will make sure that the JScrollPanes that contain the JTables occupy as much space as possible.
    Hope this helps,
    Ranga.

  • JTable in JPanel cut off

    I'm trying to put a JTable with several elements in a JPanel and it is getting cut off. I have tried extending the gridbagconstraints with ipady but no luck.
    public class PumpMonitor extends JPanel
    JTable Table1;
    PumpMonitor()
    Table1Model dm = new Table1Model();
    Table1 = new JTable( dm ) ;
    GridBagLayout gridBagLayout3 = new GridBagLayout();
    gridBagLayout3.rowHeights[0] = 300;
    Dimension size = new Dimension(300,400);
    this.setMinimumSize(size);
    this.setVisible(true);
    this.setPreferredSize(size);
    this.setMaximumSize(size);
    this.setLayout(gridBagLayout3);
    Table1.setBackground(Color.white);
    Table1.setEnabled(false);
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 1;
    c.ipady = 10;
    c.gridwidth = 100;
    c.anchor = GridBagConstraints.NORTHWEST;
    gridBagLayout3.setConstraints(hel,c);
    this.add(hel);
    this.add(Table1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 74, 500));
    class Table1Model extends AbstractTableModel
    Object[][] Table1Data =
    {"Address",new String()},
    {"Serial #" ,new String()},
    {"SW Revision" ,new String()},
    {"ETM" ,new String()},
    {"T1",new String()},
    {"T2" ,new String()},
    {"TC/Vac Gauge" ,new String()},
    {"Aux TC" ,new String()},
    {"Motor Speed",new String()},
    {"Set Values" ,new String()},
    {"Heater Pwr T1" ,new String()},
    {"Heater Pwr T2" ,new String()},
    public void setValueAt (Object value, int row, int col)
         Table1Data[row][col] = value;
         public int getColumnCount()
    return Table1Data[0].length;
    public int getRowCount()
    return Table1Data.length;
    /* public String getColumnName(int col)
    return (String)headers[col];
    public Object getValueAt(int row,int col)
    return Table1Data[row][col];
    };

    Thanks Denis.
    I did this:
    JScrollPane scroll = new JScrollPane(Table1);
    this.add(scroll, new GridBagConstraints(0, 0, 1, 3, 1.0, 1.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 74, 500));
    That works but I want to see the whole table at once. Is there something I can do to do that?

  • JTable with JPanel form as cell renderer/editor

    I have a JTable that uses a custom cell editor/renderer. The cell editor/renderer is a JPanel form with labels and text panes. As the user edits the information, I adjust the table row height (setRowHeight) and the JPanel layout manager updates the layout on the cell editor. This all seems to work fine. However, when the user exists the cell and the cell renderer is shown, it has the correct new row height but has not been correctly layed-out for the new row height. How do I force my cell renderer to be re-layout after the editor closes?

    That does not seem to work. I have done the following:
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int r, int c)
    this.table = (EditorTable) table;
    row = r;
    column = c;
    if (isSelected)
    setBackground (Preferences.selectedRowBgColor);
    else
    setBackground (formBg);
    // constructs the panel components
    setCellValue (value);
    revalidate();
    return (this);

  • JTable on JPanel on JFrame, not appearing

    I can't see the JTable that I was expecting to between the two labels, any ideas why?
    public class Workout extends JFrame {
            final String[] exercisesDoneColumnNames = {"Exercise", "# Sets", "Set 1", "Set 2", "Set 3", "Set 4", "Set 5", "Set 6", "Set 7", "Set 8", "Set 9", "Set 10"};
            private ExercisesDoneTable myModel = new ExercisesDoneTable exercisesDoneColumnNames,0);
            private JTable table = new JTable(myModel);
            public Workout() {
                super.setTitle("Workout");
                buildExerciseDoneTable();
                Toolkit tk = Toolkit.getDefaultToolkit();
                Dimension d = new Dimension();
                d = tk.getScreenSize();
                setSize((int)d.getWidth(), (int)d.getHeight());
                setLocation(0,0);
                super.setName("Workout");
                addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent evt) {   
                        System.exit(0);
                JPanel p = new JPanel();
                p.setBackground(java.awt.Color.white);
                p.add(new JLabel("left of"));
                p.add(table);
                p.add(new JLabel("right of"));
                getContentPane().add(p);
                setVisible(true);
        //helper method just splits the code to make it more readable
        private void buildExerciseDoneTable(){
            table.setPreferredScrollableViewportSize(new Dimension(500,100));
            myModel.addTableModelListener(myModel);
            table.setVisible(true);
        }

    JPanel has a default FlowLayout.
    I think you table is there, but is not displaying anything as you have specified 0 rows when creating your table model. Change that number to 1 and you will see it appear.

  • JTable on JPanel

    I have a JTable that used to have a header on a JScrollPane, until i placed the table onto a JPanel. The header of my table suddenly disappeared, just the contents of my rows remain....does anyone know why?

    If you don't put the table in a scrollpane, you have to place the header yourself.import java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.setLayout(new GridLayout(1,2));
        String[] head1 = {"One","Two","Three"}, head2={"Uno","Dos","Tres"};
        String[][] data1 = new String[10][head1.length], data2=new String[10][head2.length];
        for (int i=0; i<data1.length; i++) {
          for (int j = 0; j < data1.length; j++) data1[i][j] = "R" + i + "-C" + j;
    for (int i=0; i<data2.length; i++) {
    for (int j = 0; j < data2[i].length; j++) data2[i][j] = "F" + i + "-C" + j;
    JTable jt1 = new JTable(data1,head1), jt2 = new JTable(data2, head2);
    content.add(new JScrollPane(jt1));
    JPanel jp2 = new JPanel(new BorderLayout());
    jp2.add(jt2, BorderLayout.CENTER);
    jp2.add(jt2.getTableHeader(), BorderLayout.NORTH);
    content.add(jp2);
    setSize(600,300);
    setVisible(true);
    public static void main(String[] args) { new Test3(); }

  • JTable an JPanel

    Is it possible to display a JPanel in a cell in a JTable? I have tried but it does not show in the cell.
    Thanks / Sam

    I believe so. You could try google.
    http://www.google.com/search?q=JPanel+JTable+DefaultTableCellRenderer

  • Mapping of JTable Rows and columns and paint it to the JPanel

    Hi,
    I am using JTable and graphics object to draw the JTable on JPanel. But due to some lack of measurement I am not able to draw table cells correctly.
    Apart from this on changing the fontSize I have to redraw it according to the requirement. But when the data size increases it draws absurdly.
    I am using jTable.getCellRect() api to get the row width and height. Please help to redraw a JTable cell row and height on JPanel.
    I am also attaching a sample code with this mail.
    Thanks,
    Ajay
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.table.*;
    import java.util.*;
    import java.awt.*;
    public class SimpleTableDemo extends JPanel {
        private boolean DEBUG = false;
           private int spacing = 6;
           private Map columnSizes = new HashMap();
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
             {"Kathy", "Smith",
              "SnowboardingXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Integer(5), new Boolean(false)},
             {"John", "Doe",
              "Rowing", new Integer(3), new Boolean(true)},
             {"Sue", "Black",
              "Knitting", new Integer(2), new Boolean(false)},
             {"Jane", "White",
              "Speed reading", new Integer(20), new Boolean(true)},
             {"Joe", "Brown",
              "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
              Panel1 panel;
        public SimpleTableDemo() {
            super(new GridLayout(3,0));
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //table.setFillsViewportHeight(true);
            if (DEBUG) {
                table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        printDebugData(table);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            panel = new Panel1();
            Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(table.getWidth());
              panel.setY(0);
            panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              add(panel);
            final JComboBox jNumberComboBoxSize = new JComboBox();
              jNumberComboBoxSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "11", "12", "14", "16", "18", "20", "24", "30", "36", "48", "72" }));
            jNumberComboBoxSize.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                   jNumberComboBoxSizeActionPerformed(jNumberComboBoxSize);
              JPanel panel2 = new JPanel();
              panel2.add(jNumberComboBoxSize);
              add(panel2);
              adjustColumns();
         private void jNumberComboBoxSizeActionPerformed(JComboBox jNumberComboBoxSize)
            int fontSize = Integer.parseInt(jNumberComboBoxSize.getSelectedItem().toString());
              table.setRowHeight(fontSize);
              table.setFont(new Font("Serif", Font.BOLD, fontSize));
              Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(0);
              panel.setY(0);
           // panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              panel.repaint();
              table.revalidate();
        private void printDebugData(JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            System.out.println("Value of data: ");
            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                System.out.println();
            System.out.println("--------------------------");
          *  Adjust the widths of all the columns in the table
         public void adjustColumns()
              TableColumnModel tcm = table.getColumnModel();
              for (int i = 0; i < tcm.getColumnCount(); i++)
                   adjustColumn(i);
          *  Adjust the width of the specified column in the table
         public void adjustColumn(final int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              int columnHeaderWidth = getColumnHeaderWidth( column );
              int columnDataWidth   = getColumnDataWidth( column );
              int preferredWidth    = Math.max(columnHeaderWidth, columnDataWidth);
            panel.setWidth(preferredWidth);
              updateTableColumn(column, preferredWidth);
          *  Calculated the width based on the column name
         private int getColumnHeaderWidth(int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              Object value = tableColumn.getHeaderValue();
              TableCellRenderer renderer = tableColumn.getHeaderRenderer();
              if (renderer == null)
                   renderer = table.getTableHeader().getDefaultRenderer();
              Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
              return c.getPreferredSize().width;
          *  Calculate the width based on the widest cell renderer for the
          *  given column.
         private int getColumnDataWidth(int column)
              int preferredWidth = 0;
              int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();
              for (int row = 0; row < table.getRowCount(); row++)
                  preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));
                   //  We've exceeded the maximum width, no need to check other rows
                   if (preferredWidth >= maxWidth)
                       break;
              return preferredWidth;
          *  Get the preferred width for the specified cell
         private int getCellDataWidth(int row, int column)
              //  Inovke the renderer for the cell to calculate the preferred width
              TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
              Component c = table.prepareRenderer(cellRenderer, row, column);
              int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
              return width;
          *  Update the TableColumn with the newly calculated width
         private void updateTableColumn(int column, int width)
              final TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              width += spacing;
              //  Don't shrink the column width
              width = Math.max(width, tableColumn.getPreferredWidth());
              columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
              table.getTableHeader().setResizingColumn(tableColumn);
              tableColumn.setWidth(width);
         * 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("SimpleTableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            SimpleTableDemo newContentPane = new SimpleTableDemo();
            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();
    class Panel1 extends JPanel
        int x;
         int y;
         int width;
         int height;
         String str;
         JTable model;
        public void setModel(JTable model)
           this.model = model;
         public void setX(int x)
              this.x = x;
        public void setY(int y)
              this.y = y;
         public void setWidth(int w)
              this.width = w;
        public void setHeight(int h)
              this.height = h;
         public void setStr(String s)
              this.str = s;
        public void paint(Graphics g)
             super.paint(g);
              int initX= 0;
              for(int row=0;row < 5; ++row)
                   initX = x;
                   for (int col=0;col < 5;++col)
                        g.drawRect(x,y,width,height);
                        g.drawString(model.getModel().getValueAt(row,col).toString(),x + 10,y + 10);
                        x = x + width;
                x = initX;
                   y = y + height;
    };

    an easy way would be to use setSize()

  • How to outline selected cells during drag and drop in the jtable

    Hi,
    I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
    Can anybody give me a tip, where to read more about this problem or even better, give an example...
    I have the following situation:
    1.Table has 10 rows and 10 columns
    2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
    3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
    4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
    5.rectangular disappears when dropped
    Regards,
    Primoz

    In "createTransferable" you can create a drag image
    which you can paint in "dragOver" and clear in "drop" method of DropTarget :
    package dnd;
    * DragDropJTableCellContents.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    public class DragDropJTableCellContents extends JFrame {
        public DragDropJTableCellContents() {
            setTitle("Drag and Drop JTable");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
            setSize(400, 300);
            setLocationRelativeTo(null);
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            for (int i = 0; i < 10; i++) {
                model.addColumn("Column "+i);
            for (int i = 0; i < 10; i++) {
                String[] rowData = new String[10];
                for (int j = 0; j < 10; j++) {
                    rowData[j] = tableId + " " + i + j;
                model.addRow(rowData);
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setCellSelectionEnabled(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDragEnabled(true);
            TableTransferHandler th = new TableTransferHandler();
            table.setTransferHandler(th);
            table.setDropTarget(new TableDropTarget(th));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DragDropJTableCellContents().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            @Override
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            @Override
            public boolean importData(JComponent c, Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            @Override
            protected Transferable createTransferable(JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                return buff.toString();
            protected void importString(JComponent c, String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    model.setValueAt(string, target.getSelectedRow(), colCount);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(JTable table, Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTable table, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

  • Custom Cell Renderer issue in Custom JTable

    I have CustomeTable extends JTable which renders different UI Components like (JTextField/ ComboBox /JButton/JCheckBox) in *"single column*" so i have overridden *getCellRenderer* and *getCellEditor methods.*
    Now my Custom Table changes contextually by selecting different nodes in JTree similar to Windows Explorer
    *The problem is Some times When i Click Button & then i click other Node which displays other UIComponents old components (Button is painted) instead of new COmponent(JTextfield or ...)*
    *For each UI Renderer i have called its repaint() method still this issue is noticed not frequentlly but yes occasionally.*

    Following are some of my Custom Text / Combo Renderer / Password / Button to display different UI Components @ Column 2 as per my above Code
    private class MyDefaultRenderer implements TableCellRenderer {
            private JTextField l;
            private Border borderPrevious;
            public MyDefaultRenderer() {
                l = new JTextField();
                borderPrevious = l.getBorder();
            public Component getTableCellRendererComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus,
                    int row,
                    int column) {
                PropertyInfoType propertyType = propertyInfoList.get(row).getType();
                if (ConfigCommonPropertyPanel.isInputEditable && !propertyInfoList.get(row).isReadOnly()) {
                String tempVal = "";
                if (value != null && value instanceof String) {
                    tempVal = value.toString();
                l.setText(tempVal);
                l.setOpaque(true);
                l.revalidate();
                l.repaint();
                return l;
            public Object getCellEditorValue() {
                return l.getText();
           private class ButtonRenderer implements TableCellRenderer {
            JPanel buttonPanel;
            JButton button;
            public ButtonRenderer() {
                buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                button = new JButton(getAdminUIMsg(168));
                buttonPanel.setOpaque(true);
                buttonPanel.add(button);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                button.setFont(LNFManager.getThemeForComponent(table).getBodyText());
                buttonPanel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                buttonPanel.revalidate();
                buttonPanel.repaint();
                return buttonPanel;
        private class ButtonEditor extends JButton implements TableCellEditor, ActionListener {
            int rowIndex;
            int columnIndex;
            JTable table;
            JPanel panel;
            public ButtonEditor() {
                super("Validate Database");
                panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                addActionListener(this);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
                rowIndex = row;
                columnIndex = column;
                setOpaque(true);
                panel.setOpaque(true);
                panel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                setFocusable(true);
                panel.repaint();
                panel.add(this);
                return panel;
            public Object getCellEditorValue() {
                return this.isSelected();
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                return true;
            public void cancelCellEditing() {
            public void addCellEditorListener(CellEditorListener l) {
            public void removeCellEditorListener(CellEditorListener l) {
            public void actionPerformed(ActionEvent e) {
                              try{
    // Some Business Logic To check my Database / LDAP Connections on Button Click
                                 }catch( Exception ex){
                                  } finally{
                                            stopCellEditing();
                                            transferFocus();
                   +Shouldnt i call repaint() on a specific Component for a Specific renderer ?+
    My Code works perfectly 99 % of the times ..
    But very rarely when i click My Button On my Custom Table say
    When i click NODE A - which displays different UI in Right Split Info
    Row 2 Column 2 - has Validate Button
    Then i Click NODe B - Which displayes Contextual UI Components
    Row 2 Column 2 should display TextBox (as expected)
    but due to some rendering issue its Displaying same Validate Button
    I have debugged and verified my logic to call renderer is perfect.
    My rest of rows /columns displays appropriate UI Components except the
    position of Button .
    I think after my Button Editor is Invoked & i perform some business logic Button renderer is not getting invoked ???

  • Inserting row in JTable (runtime)

    i need to inserting row in JTable in runtime so tell me what it do

    dear farhanaj ,
    try this code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    /* <applet code=tableadd.class width=200 height=200>
    </applet>
    public class tableadd extends JApplet implements ActionListener
    Object[] data = new Object[5];
    DefaultTableModel defaulttablemodel = new DefaultTableModel();
    JTable jtable=new JTable(defaulttablemodel);
    JPanel jpanel= new JPanel();
    private     JPanel          topPanel,jpPanel;
    public     JTable          table;
    JButton jbutton1 = new JButton("create new row");
    JButton jbutton2 = new JButton("create new col");
    //JButton jbutton1=new Jbutton("r"),jbutton2=new Jbutton("c");
    public tableadd()
    for(int column=0 ; column<5 ; column++)
    defaulttablemodel.addColumn("column" + column);
    for(int row=0 ; row<5;row++)
    for(int column=0 ;column<5;column++)
    data[column]="cell" row "," + column;
    defaulttablemodel.addRow(data);
    //getContentPane().add(new JScrollPane(jtable) ,BorderLayout.CENTER);
    //getContentPane().add(new JPanel() ,BorderLayout.SOUTH);
    int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(jtable , v, h);
    getContentPane().add(jsp, BorderLayout.CENTER);
    topPanel = new JPanel();
    jpPanel=new JPanel();
    topPanel.setLayout( new BorderLayout() );
    getContentPane().add(topPanel,BorderLayout.NORTH);
    getContentPane().add(jpPanel,BorderLayout.SOUTH);
    jpPanel.add(jbutton1);
    jpPanel.add(jbutton2);
    jbutton1.addActionListener(this);
    jbutton2.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jbutton1)
    int numberrows = defaulttablemodel.getRowCount();
    int numbercolumns=defaulttablemodel.getColumnCount();
    Object[] data = new Object[numbercolumns];
    for(int column=0 ; column<numbercolumns;column++)
    data[column]="cell" numberrows "," +column;
    defaulttablemodel.addRow(data);
    else
    if (e.getSource() ==jbutton2)
    int numberrows=defaulttablemodel.getRowCount();
    int numbercolumns=defaulttablemodel.getColumnCount();
    defaulttablemodel.addColumn("column" + numbercolumns);
    for(int row=0; row<numberrows ; row++)
    defaulttablemodel.setValueAt("cell" row "," +numbercolumns ,row , numbercolumns);
                   System.out.println(row);
    //jtable.sizeColumnsToFit(0);

  • How to force update jtable display

    I am trying to add some filtering funtionality to my swing application that uses a JTable. What I do is to filter the JTable's datamodel, and call repaint() on the jtable and JPanel, and do jframe.pack(); Sometimes it works, sometimes it doesn't. I check the jtable model, and it is being updated properly. I guess it is a GUI update problem. Is there a better way to force the whole app's GUI to be updated?
    //update tableModel
    //repaint() jtable;
    //repaint() jpanel;
    jf.pack();

    A couple questions
    1. Did you write your own table model? Not calling fireTableDataChanged() can cause problems in this case.
    2. Do you update the table from a thread? You might need to put the updates on the event thread (SwingUtilities.invokeNoow() or invokeLater()) or manually call fireTableDataChanged() (I'm not sure if this needs to happen on the event thread)

  • New jTable problem.. HELP..

    I have the following function of new jTable is being created but it doesn't work:
    public void setTable1(){
        /* Renew table component*/
        jTable1 = new JTable(rs.AttSize,2);
        /* Put jTable into JScrollPane and then into jPanel2 */
        JScrollPane scrollpane = new JScrollPane(jTable1);
        TableColumn column = null;
        column = jTable1.getColumnModel().getColumn(0);
        column.setHeaderValue("No");
        column = jTable1.getColumnModel().getColumn(1);
        column.setPreferredWidth(400);
        column.setHeaderValue("Attribute Name");
        jPanel2.add(scrollpane);
        jPanel2.validate();
    }How can I remove previous jTable1? and add new jTable into jPanel, my code doesn't show up the new jTable1.. I'm dying to code rite now.. Please help me...

    Bingoo.. I'm alive again.. found this link:
    http://forum.java.sun.com/thread.jsp?thread=194107&forum=57&message=635591
    from Author: lalo79. Thanks...
    and my function suppose to be like:
    protected void setTable1(){
        /* new jTable1 component to jPanel2 */
        jTable1 = new JTable(model);
        TableColumn column = null;
        column = jTable1.getColumnModel().getColumn(1);
        column.setPreferredWidth(400);  
        scrollpane = new JScrollPane(jTable1);
        jPanel2.add(scrollpane);
        /* Remove all row for inserting new value */
        while (jTable1.getRowCount() > 0)
          ((DefaultTableModel)jTable1.getModel()).removeRow(0);
        /* put value to the new row */
        for(int i=0;i<rs.AttSize;i++){
          model.addRow(new Object[] {String.valueOf(i+1),rs.ArrayAtts[0]});
    jPanel2.updateUI();
    jPanel2.validate();
    come back to work again..

Maybe you are looking for