JTable without JScrollPane behavior crippled

I want column width of JTable t1 goes parallel with the width resizing on
JTable t2. If tables are put in JScrollPanes, this has no problem. But if I put
those tables in simpler container, which is JPanel in this case, t2 shows a
funny behavior -- with user's mouse operation on t2 column, their width
never changes but t1 column width changes properly. Could I have
succeeded in communicating the funniness with these sentences?
Please try this code and give cause and solution if you could:
import java.awt.*;
import java.beans.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
public class TableColumnWidthResize{
  JFrame frame;
  JTable t1, t2;
  TableColumnModel tcm1, tcm2;
  Enumeration columns1, columns2;
  String[] t1h = {"Road", "Length", "City"};
  String[][] t1c
   = {{"NW2", "800", "Dora"},
     {"Iban", "600", "Weiho"},
     {"ENE2", "500","Porso"}};
  String[] t2h = {"Flower", "Curse", "Priest"};
  String[][] t2c
    = {{"Fang", "7.00", "EggChar"},
      {"Shaoma", "5.00", "ScaCra"},
      {"Jiao", "4.00", "PorCabb"}};
  public TableColumnWidthResize(){
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = frame.getContentPane();
    con.setLayout(new GridLayout(2, 1));
    t1 = new JTable(t1c, t1h); //target table -- 'resized from t2'
    t2 = new JTable(t2c, t2h); //source table -- 'initiate resize'
    t1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    t2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /* you can compare two methods of table placement*/
    useScrollPane(t1, t2, con); //works fine
//    nouseScrollPane(t1, t2, con); //resize behavior weird
    frame.pack();
    frame.setVisible(true);
    tcm1 = t1.getColumnModel();
    tcm2 = t2.getColumnModel();
    columns2 = tcm2.getColumns(); // all columns of t2
    TableColumnListener tcl = new TableColumnListener();
    while (columns2.hasMoreElements()){
      TableColumn tc = (TableColumn)(columns2.nextElement());
      tc.addPropertyChangeListener(tcl);
  class TableColumnListener implements PropertyChangeListener{
    // achieve 'interlocking-column-resizing' from t2 to t1
    public void propertyChange(PropertyChangeEvent pce){
      TableColumn tc = (TableColumn)(pce.getSource());
      int i = tc.getModelIndex();
      tcm1.getColumn(i).setPreferredWidth(tc.getWidth());
  void useScrollPane(JTable ta, JTable tb, Container c){
    JScrollPane jsc1 = new JScrollPane(ta);
    ta.setPreferredScrollableViewportSize(new Dimension(225, 50));
    JScrollPane jsc2 = new JScrollPane(tb);
    tb.setPreferredScrollableViewportSize(new Dimension(225, 50));
    c.add(jsc1); c.add(jsc2);
  void nouseScrollPane(JTable ta, JTable tb, Container c){
    JPanel p1 = new JPanel(); JPanel p2 = new JPanel();
    p1.setLayout(new BorderLayout());
    p2.setLayout(new BorderLayout());
    p1.add(ta.getTableHeader(), BorderLayout.PAGE_START);
    p2.add(tb.getTableHeader(), BorderLayout.PAGE_START);
    p1.add(ta, BorderLayout.CENTER);
    p2.add(tb, BorderLayout.CENTER);   
    c.add(p1); c.add(p2);
  public static void main(String[] args){
    new TableColumnWidthResize();
}

Hey hiwa,
I don't see anything mysterious going on. If you think about it, how many components can we resize at run-time/dynamically with a mouse - none, except for the columns in a JTable, Frames and Dialogs. Note the latter two are top level and answer to no-one (except the screen i guess).
If you have ever implemented a component that can be 'dragged' and manipulated by the mouse, have you ever done so outside, that is, not using a JScrollPane? I doubt it.
I do not think it has anything to do with mouse precision. Maybe you are just experiencing undefined behaviour, unreliable behaviour. I imagine the Swing team didn't bother themselves with a usage scenario that would yield lesser results for a simple task. Using AUTO_RESIZE_OFF and requesting more room than the Container has to offer may upset that containers LayoutManager i.e. their algorithms may contain code that will shrink child components to fit, or nab space from sibling components.
Basically, in my experience, how ever long it takes me to realise it, when Swing goes on the blink it is usually a programming error.
BTW, did my suggestion work ok?
Sorry if I come across forceful. I'm glad I read and tested your code - the synchronization effect will be very useful.
Warm regards,
Darren

Similar Messages

  • JTable without column headers?

    I want a JTable without the column headers.
    How can i do this?
    Cheers?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         String[] head = {"","",""};
         String[][] data = {{"0-0","0-1","0-2"},
                       {"1-0","1-1","1-2"},
                       {"2-0","2-1","2-2"}};
         JTable myTable = new JTable(data,head);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         content.add(new JScrollPane(myTable), BorderLayout.CENTER);
         setSize(200,200);
         show();
        public static void main(String[] args) { new Test(); }
    }

  • Jtable without column header

    Hi all,
    I have searched for jtable without column header... and if it´s possible how can I make?
    thanks

    Override JTable#configureEnclosingScrollPane() to do nothing or remove the table header manually ( jScrollPane.setColumnHeader(null) ) after you added the table to the scroll pane.

  • Custom column headers for JTable in JScrollPane

    I want a heirachical header structure on a scrolled JTable. I've successfully generated a second JTableHeader which moves it's tabs with the normal header. If I add the secondary JTableHeader into the container above the whole scroll pane it's does almost what I want, but it's not quite correctly aligned.
    What I want to do is to put both the automaticaly generated JTableHeader and my extra one into the JScrollPane's column header area.
    I wrapped the two headers together into a vertical Box and tried calling the setColumnHeaderView() on the scrollpane, and then creating a JViewport and using setColumnHeader(). Niether seems to have any effect. The basic table header obstinately remains unaltered.
    There seems to be some special processing going on when JTable and JScrollPane get together, but I can't understand how replacing the column header viewport can be ineffective.

    Thanks. I think I've just cracked it more thoroughly, though. [I found this bug report|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5032464]. This has guided me to a work-around that seems stable so far. I'm using an extended JTable class anyway (mostly to do with table header width behaviour). I've added a field to my own table class and the following override:
    The trick is to work out where the dirty deed is done, having search all the scroll pane related classes for special casing JTable.
    public class STable extends JTable {
        @Override
        protected void configureEnclosingScrollPane() {
            if (secondaryHeader == null) {
                super.configureEnclosingScrollPane();
            } else {
                Container p = getParent();
                if (p instanceof JViewport) {
                    Container gp = p.getParent();
                    if (gp instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane) gp;
                        // Make certain we are the viewPort's view and not, for
                        // example, the rowHeaderView of the scrollPane -
                        // an implementor of fixed columns might do this.
                        JViewport viewport = scrollPane.getViewport();
                        if (viewport == null || viewport.getView() != this) {
                            return;
                        JPanel hdrs = new JPanel();
                        hdrs.setLayout(new BorderLayout());
                        hdrs.add(secondaryHeader.getHeader(), BorderLayout.NORTH);
                        hdrs.add(getTableHeader(), BorderLayout.SOUTH);
                        scrollPane.setColumnHeaderView(hdrs);
                        //  scrollPane.getViewport().setBackingStoreEnabled(true);
                        Border border = scrollPane.getBorder();
                        if (border == null || border instanceof UIResource) {
                            Border scrollPaneBorder =
                                    UIManager.getBorder("Table.scrollPaneBorder");
                            if (scrollPaneBorder != null) {
                                scrollPane.setBorder(scrollPaneBorder);
        }I'm hopeful that will prevent the column header view from being overwritten by later layout operations.

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • Print JTable without border

    Possibly a simple question, I want to print a JTable without showing the surrounding border. I can remove the gridlines within the table but the border surrounding the table still comes out when I print, by calling the JTable.print() method
    Thanks

    I believe you cannot do anything about it, since the black border is hard-coded in the last lines of TablePrintable.print():
    // draw a box around the table
    g2d.setColor(Color.BLACK);
    g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);

  • JTable within JScrollPane (setting BGColor)

    Hello,
    if the JScrollPane is larger than the contained JTable. How can I set the background-color of the arised gap?
    Neither JTable.setBackground(...) nor JScrollPane.setBackground(...) show any effect, i.e. the background-color doesn't change.
    Is there a proper way to avoid this gap, without scrollbars or knowning the exact size of the JTable?
    Yours truly, Raffael Vogler

    http://search.java.sun.com/search/java/index.jsp?qt=%2Btitle%3Ajscrollpane+%2Btitle%3Abackground&nh=10&qp=&rf=1&since=&country=&language=&charset=&variant=&col=javaforums

  • How to get the value from a cell in jTable without click "enter" or "tab"

    Hi guys,
    I have a simple question. I have a jTable in my screen and when editing a value, but without click "enter" or "tab" I want to get the new value. I have a button update and after editing the value I click the button "update" and I want the new value to be store in my table. If try to get the selected value it is giving the old value. How can I implement this? Any idea? I hope I was clear.
    Thanks

    [Table Stop Editing|http://www.camick.com/java/blog.html?name=table-stop-editing]

  • JTable in JScrollpane doesn't appear

    Hi,
    Maybe, it's already asked 1000 times on this forum but I didn't found the right solution.
    My problem :
    I've created a JPanel with a JScrollpane.
    When I create the JScrollpane immediately with a JTable it works fine, the JTable appears.
    Now I try to add the JTable dynamically to the JScrollpane.
    The JTable doesn't appear.
    I've tried already the repaint, validate methods but that changes nothing.
    Can anyone tell me how I can solve my problem ?
    Thanx in advance,
    Piet

    I trust you are adding it like this:
    myJScrollPane.getViewport().add(myJTable);
    not like this:
    myJScrollPane.add(myJTable);

  • JTable in JScrollPane auto resize refresh problem

    Hello,
    I have a JTable in a JScrollPane. Number of rows is changing.
    I'm using the following to auto-resize JScrollPane.
    public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
             }There is a JButton, which adds an empty row to the JTable. It all works fine, except the auto-resize when a new row is added. I want all rows of JTable to be visible, with no scrollbars present. I tried repaint(), revalidate(), addNotify(). What should I do?
    Thanks.

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • Resize jtable in jscrollpane

    Hi,
    I have a frame containing a JTable and a panel with buttons. When the window gets resized, I would like that the jtable takes the extra space and that the button panel stays the same. How can I do that? The jtable panel is already the "Center" and both panels stay the same...
    Thanks,
    Marie
    Here's the code:
    package test;
    import javax.swing.*;
    import java.awt.AWTEvent;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class Testframe extends JFrame {
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JPanel tablePanel = new JPanel();
        //Button panel
        private JButton applyTableBt = new JButton("Generate Table");
        private JButton addBt = new JButton("Add");
        private JButton editBt = new JButton("Edit");
        private JButton deleteBt = new JButton("Delete");
        private JButton matchBt = new JButton("Find");
        private JButton saveBt = new JButton("Save to file");
        private JButton loadBt = new JButton("Load from file");
         * Constructor.
         * @param a_parent Frame
        protected Testframe() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
                this.setResizable(true);
                this.setVisible(true);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
         * Initialization of the dialog.
         * @throws Exception
        private void jbInit() throws Exception {
            this.setTitle("Pattern management - CAT");
            Object[][] data = { {"11", "12", "13", "14", "15", "16", "17", "18"},
                              {"21", "22", "23", "24", "25", "26", "27", "28"}
            Object[] names = {"col1", "col2", "col3", "col4", "col5", "col6",
                             "col7", "col8"};
            JTable table = new JTable(data, names);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //table.setColu
            TableColumnModel colModel = table.getColumnModel();
            for (int i = 0; i < table.getColumnCount(); i++) {
                TableColumn column = colModel.getColumn(i);
                column.setPreferredWidth(511);
            JScrollPane scrollPane = new JScrollPane(table);
            tablePanel.add(scrollPane);
            //Layout = vertical box with vertical gap
            buttonPanel.setLayout(new GridLayout(7, 1, 0, 5));
            buttonPanel.add(applyTableBt);
            buttonPanel.add(addBt);
            buttonPanel.add(editBt);
            buttonPanel.add(deleteBt);
            buttonPanel.add(matchBt);
            buttonPanel.add(saveBt);
            buttonPanel.add(loadBt);
            //mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
            this.setContentPane(mainPanel);
         * Overrides this class to call the good method when the dialog is closed.
         * @param a_windowE WindowEvent
        protected void processWindowEvent(WindowEvent a_windowE) {
            //If it is a request to close the window (X)
            if (a_windowE.getID() == WindowEvent.WINDOW_CLOSING) {
                cancel();
            super.processWindowEvent(a_windowE);
         * Closes the dialog.
        private void cancel() {
            dispose();
        private static void createAndDisplayFrame() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            new Testframe();
        public static void main(String[] args) {
            createAndDisplayFrame();
    }

    try changing these lines
    mainPanel.add(tablePanel, BorderLayout.CENTER);
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    this.setContentPane(mainPanel);
    to this
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(mainPanel, BorderLayout.EAST);

  • Jtable (in Jscrollpane) headers missing????

    hello,
    i need to show the results of a resultset in a jtable. i am putting the table in a jscrollpane... but still the headers dont show up. i have tested the array "headers" (Object[] headers) and is full with the correct data.
    what is missing??
    JTable table = new JTable(data,headers);
            table.setSize(jScrollPaneResultados.getSize());
            jScrollPaneResultados.add(table);
            table.setFillsViewportHeight(true);thank�s

    The scrollPane.add(...) method doesn't work the way you expect it to.
    You can use the setViewportView(...) method, or you can read the JTable API for an example of adding a table to the scrollpane when the scrollpane is created.

  • JTable in jScrollPane

    Hello, I am developing an application in Netbeans (Swing) with JDBC to connect mySQL. I got a question about a jTable in a jScrollPane. I read from my database and put the resultSet into a dinamical jTable. In the same form, I got a jTextField, where the user can input a code or a name to search in the jTable. When I find the code in the jTable I can select the row to remark the result. The problem I got is when the found code is not showing in the view of the table. So what I want to do, if it is possible, is automatically move the scroll to show the row I have selected; this way, the user don't have to move the scroll along the table (which could have a lot of rows). I have thought another solution could be show another frame with the data of selected row, but I want to try the first one.
    If you know how can I do this please, help me.
    I am sorry if my english is not very well. I hope you can understand my question.
    Thanks

    scphan wrote:
    BigDaddyLoveHandles wrote:
    JScrollPane scroll = new JScrollPane(new JTable(...));
    or scroll.getViewport().setView( new JTable(...) );(no difference implied)So do it the simpler way.

  • JTable in JScrollPane, preferred size

    When I put a JTable in a JScrollPane, the JScrollPane seems to want to be very big. How does the scroll pane determine its size? run this code for an example..
    import javax.swing.*;
    public class TestPanel extends JPanel
    public TestPanel()
         add(new JScrollPane(new JTable(1,1)));
    public static void main(String args[])
         JFrame f = new JFrame("big table test");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         TestPanel thePanel = new TestPanel();
         f.setContentPane(thePanel);
         f.pack();
         f.show();

    public class TestPanel extends JPanel {
      public TestPanel() {
        JTable jt = new JTable(1,1);
        jt.setPreferredScrollableViewportSize(new Dimension(100,100));  // Do this
        JScrollPane jsp = new JScrollPane(jt);
        jsp.setPreferredSize(new Dimension(100,100));  //OR this
        add(new JScrollPane(new JTable(1,1)));
    }

  • Confirming information in JTable without TAB?

    Hi all,
    I am using a JTable in my application, but I discovered you have to press 'TAB' or click on another row of the JTable to confirm all the data of the JTable.. Is there a way to solve this problem, so that all data are available without doing an extra event?
    I hope somebody can help me. Thanks!
    Tongue.

    I reckon you've got an editable table. Add this line:
    yourJtable.putClientProperty("terminateEditOnFocusLost" , Boolean.TRUE);

Maybe you are looking for

  • Error adding Goods Receipt PO based on Purchase Order

    I am working on an add-on that was working against a 2005A version of SAP Business One and I am upgrading it to run against a 2007A Company (PL41) I am receiving strange errors when testing the add-on. I can add a Purchase order not based on a Goods

  • Some error when running WD Application accessing ABAP Functions

    Dear friends, I try to deploy and run the Example Application "TutWD_FlightList_Init", but it's always display the error like the following (see at the bottom of this message). By the way I'll give your more informations like this: 1) My NWDS and SAP

  • Reports Required in MM

    Dear SAP Experts, My Client is required as follows report in MM. We have to tell input to technofunctional consultants. Accordingly give me the necessary inputs to get these reports in SAP MM. 1) Consumption report, date to date, & Group  & Item wise

  • Java RMI and Server Crash

    Hi, I just want to know if there is a possibility to let the Clients of a rmi based Client-Server-archtiecture know, when a Server crashes. The problem is, that the names are still bound in the rmi-registry of a server, but the server is not able to

  • One Function Absent When Playing Timeline To TV.

    This is not so much a serious problem as a minor curiosity. I use a Datavideo DAC 100 A/D Converter to play my timeline on a TV. It functions beautifully. However, yesterday I noticed a slight peculiarity. I was using the Left and Right Arrow keys wh