Resize JTable in JTabbedPane

Given the FileTableDemo from the Java Foundation Class in a Nutshell book.(O'Reilly) Chapter 3 page 51 in my addition.
I have modified the example to place the JTable in a JTabbedPane. Now when the window (JFrame) is resized by the user the JTable no longer resizes. How do I passing the "resizing" into the component (JTable) placed in the JTabbedPane?
Here is the code: My deviation from the example is enclosed in "///////////KBS" and of course the line frame.getContentPane().add(myTP, "Center"); where "pane" has been replaced with "myTP"
Thanks Brad
import javax.swing.*;
import javax.swing.table.*;
import java.io.File;
import java.util.Date;
public class FileTableDemo
public static void main(String[] args)
// Figure out what directory to display
File dir;
if (args.length > 0)
dir = new File(args[0]);
else
dir = new File(System.getProperty("user.home"));
// Create a TableModel object to represent the contents of the directory
FileTableModel model = new FileTableModel(dir);
// Create a JTable and tell it to display our model
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
pane.setBorder(BorderFactory.createEmptyBorder(60,20,20,20));
////////KBS
JTabbedPane myTP = new JTabbedPane();
JPanel myOne = new JPanel();
JPanel myTwo = new JPanel();
myOne.add(pane);
myTP.add("One", myOne);
myTP.add("Two", myTwo);
////////KBS
// Display it all in a scrolling window and make the window appear
JFrame frame = new JFrame("FileTableDemo");
frame.getContentPane().add(myTP, "Center");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// The methods in this class allow the JTable component to get
// and display data about the files in a specified directory.
// It represents a table with six columns: filename, size, modification date,
// plus three columns for flags: direcotry, readable, writable
class FileTableModel extends AbstractTableModel
protected File dir;
protected String[] filenames;
protected String[] columnNames = new String[] {
"name",
"size",
"last modified",
"directory?",
"readable?",
"writable?"
protected Class[] columnClasses = new Class[] {
String.class,
Long.class,
Date.class,
Boolean.class,
Boolean.class,
Boolean.class
// This table model works for any one given directory
public FileTableModel(File dir)
this.dir = dir;
this.filenames = dir.list();
// These are easy methods
public int getColumnCount()
return 6;
public int getRowCount()
return filenames.length;
// Information about each column
public String getColumnName(int col)
return columnNames[col];
public Class getColumnClass(int col)
return columnClasses[col];
// The method that must actually return the value of each cell
public Object getValueAt(int row, int col)
File f = new File(dir, filenames[row]);
switch(col)
case 0: return filenames[row];
case 1: return new Long(f.length());
case 2: return new Date(f.lastModified());
case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
default: return null;
}

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

Similar Messages

  • Dynamically resize JTable cell to fit a JList

    Hi!
    I've been banging my head trying to add some dynamic behavior to a TableCellEditor. In short I'm trying trying to make it resize the height of the current row (the one it is in) to reflect the changes made to the JList used to let the user edit the cells value (which is a list of items).
    I've come across some threads dealing with the problem of resizing a cell to fit its content. This however is usually only done once (in the 'getTableCellEditorComponent' function) and so only provides half the answer. Also, since the editor is only active during cell editing I've been trying to make it revert to the old cell height after the editing is done.
    So far I have not come up with any decent solution to this problem and was hoping someone out there might have an idea or have read something similar and can point me to something helpful... anyone?
    Cheers!
    Teo

    The Swing tutorial on[url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables shows how to dynamically change the size to Table Columns.
    If you need help calculating the acutal size then try searching the forum. Using keywords "resize jtable column" (keywords I took directly from your topic title) I found some promising postings.

  • Want to resize JTable after run programe by mouse

    I want to resize JTable by mouse after run programe.
    (want to resize Jtable anytime)
    please help me. thank you

    You cannot do that directly, you can only cause the container which holds the JTable to change size. As long as that container has a LayoutManager like BorderLayout then the JTable will resize with the container (Like a JFrame)

  • JTable on JTabbedPane

    Hi,
    I was wondering how you would add a JTable onto a JTabbedPane?
    Thanks

    import javax.swing.*;
    import java.awt.*;
    public class TabTable {
         TabTable(){
              JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame f = new JFrame("JTable in JTabbedPane ...");
              JTabbedPane tab = new JTabbedPane();
              Object table [][] = {{"Singaravelan","21","MALE"},{"Devanderan","19","MALE"}};
              String column [] = {"NAME","AGE","SEX"};
              JTable jtable = new JTable(table,column);
              JPanel panel = new JPanel();
              panel.setLayout(new FlowLayout());
              panel.add(jtable);
              tab.addTab("Table 1",panel);
              tab.addTab("Table 2",new JLabel("Table 2",JLabel.CENTER));
              tab.addTab("Table 3",new JLabel("Table 3",JLabel.CENTER));
              f.getContentPane().add(tab);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(500,500);
              f.setVisible(true);
         public static void main(String args[]){
              new TabTable();          
    }

  • Issue with re-sizing JTable Headers, JTabbedPane and JSplit pane

    Ok, hopefully I'll explain this well enough.
    In my Swing application I have a split pane, on the left hand side is a JTable and on the right hand is a JTabbedPane. In the tabs of the JTabbedPane there are other JTables.
    In order to make the rows in the JTable on the left and the JTable(s) on the right line up, the Table Header of all the tables is set to the size of the tallest (deepest?) table header.
    Hopefully so far I'm making sense. Now to get to the issue. One of the tables has a number of columns equal to the value on a NumberSpinner (it represents a number of weeks). When this value is changed the table is modified so that it contains the correct number of columns. As the table is re-drawn the table header goes back to its default size so I call my header-resize method to ensure it lines up.
    The problem is this: if I change the number of weeks when selecting a tab other than the one containing my table then everything is fine, the table header is re-sized and everything lines up. If I change the number of weeks with the tab containing the table selected, the column headers stay at their standard size and nothing lines up.
    To make things more complicated, I also put System.out.println's in as every method called in the process to obtain the size of the table header. And every println returned the same height, the height the table header should be.. So I'm really confused.
    Could anyone shed any light on this?
    Thanks.

    Okay I managed to solve the problem by explicitly revalidating and repainting the table header.
    Not sure why it wasnt doing it properly for that table when all the others where fine.
    Oh well...

  • Resize Jpanel and JtabbedPane

    Hi All,
    i implement a resize process on jpanel that include JtabbedPane inside.
    it working fine except one thing.
    when i resize my panel it work fine, until some point it start to shrink and get smaller.
    i think it getting shrink because im getting to the end of my dialog.
    i want to avoid this beheviour and let the tabbedpanel extend as much as possible:
    this is my code:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GraphicsConfiguration;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.HeadlessException;
    import java.awt.Point;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.SwingUtilities;
    public class BaseMain extends JFrame {
         Point sp;
         int     jPanelStartHeight;
         int     jPanelStartWidth;
         int     jTabPaneStartHeight;
         int     jTabPaneStartWidth;
         Point offset;
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JPanel jPanel = null;
         private JTabbedPane jTabbedPane = null;
         private JPanel jPanel1 = null;
         private JTabbedPane jTabbedPane1 = null;
         private JPanel jPanel2 = null;
         private JTabbedPane jTabbedPane2 = null;
         public BaseMain() throws HeadlessException {
              // TODO Auto-generated constructor stub
              super();
              initialize();
         public BaseMain(GraphicsConfiguration arg0) {
              super(arg0);
              // TODO Auto-generated constructor stub
              initialize();
         public BaseMain(String arg0) throws HeadlessException {
              super(arg0);
              // TODO Auto-generated constructor stub
              initialize();
         public BaseMain(String arg0, GraphicsConfiguration arg1) {
              super(arg0, arg1);
              // TODO Auto-generated constructor stub
              initialize();
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getJPanel() {
              if (jPanel == null) {
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.fill = GridBagConstraints.BOTH;
                   gridBagConstraints1.weighty = 1.0;
                   gridBagConstraints1.weightx = 1.0;
                   gridBagConstraints1.gridheight=3;
                   jPanel = new JPanel();
                   jPanel.setLayout(new BorderLayout());
                   jPanel.setBorder(BorderFactory.createLineBorder(Color.black, 2));
                   jPanel.add(getJTabbedPane(),BorderLayout.SOUTH/* gridBagConstraints1*/);
                   jPanel.addMouseListener(new java.awt.event.MouseAdapter() {
                        public void mousePressed(java.awt.event.MouseEvent e) {
                             System.out.println("mousePressed()"); // TODO Auto-generated Event stub mousePressed()
                             //original size
                             jPanelStartHeight = jPanel.getHeight();
                             jPanelStartWidth  = jPanel.getWidth();
                             jTabPaneStartHeight = jTabbedPane.getHeight();
                             jTabPaneStartWidth  = jTabbedPane.getWidth();
                              offset = SwingUtilities.convertPoint(e.getComponent(),e.getPoint(),jPanel);
                   jPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                        public void mouseDragged(java.awt.event.MouseEvent e) {
                             System.out.println("mouseDragged()"); // TODO Auto-generated Event stub mouseDragged()
                             Point p = SwingUtilities.convertPoint(e.getComponent(),e.getPoint(), jContentPane);
                             jPanel.setSize(jPanelStartWidth,p.y+jPanelStartHeight);
                             jTabbedPane.setSize(jTabPaneStartWidth,p.y+jTabPaneStartHeight);
                             jPanel.setLocation(0/*p.x-offset.x*/,p.y-offset.y);
              return jPanel;
          * This method initializes jTabbedPane     
          * @return javax.swing.JTabbedPane     
         private JTabbedPane getJTabbedPane() {
              if (jTabbedPane == null) {
                   jTabbedPane = new JTabbedPane();
                   jTabbedPane.addTab(null, null, getJPanel1(), null);
                   jTabbedPane.addTab(null, null, getJPanel2(), null);
              return jTabbedPane;
          * This method initializes jPanel1     
          * @return javax.swing.JPanel     
         private JPanel getJPanel1() {
              if (jPanel1 == null) {
                   GridBagConstraints gridBagConstraints = new GridBagConstraints();
                   gridBagConstraints.fill = GridBagConstraints.BOTH;
                   gridBagConstraints.weighty = 1.0;
                   gridBagConstraints.weightx = 1.0;
                   jPanel1 = new JPanel();
                   jPanel1.setLayout(new GridBagLayout());
                   jPanel1.add(getJTabbedPane1(), gridBagConstraints);
              return jPanel1;
          * This method initializes jTabbedPane1     
          * @return javax.swing.JTabbedPane     
         private JTabbedPane getJTabbedPane1() {
              if (jTabbedPane1 == null) {
                   jTabbedPane1 = new JTabbedPane();
              return jTabbedPane1;
          * This method initializes jPanel2     
          * @return javax.swing.JPanel     
         private JPanel getJPanel2() {
              if (jPanel2 == null) {
                   GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                   gridBagConstraints2.fill = GridBagConstraints.BOTH;
                   gridBagConstraints2.weighty = 1.0;
                   gridBagConstraints2.weightx = 1.0;
                   jPanel2 = new JPanel();
                   jPanel2.setLayout(new GridBagLayout());
                   jPanel2.add(getJTabbedPane2(), gridBagConstraints2);
              return jPanel2;
          * This method initializes jTabbedPane2     
          * @return javax.swing.JTabbedPane     
         private JTabbedPane getJTabbedPane2() {
              if (jTabbedPane2 == null) {
                   jTabbedPane2 = new JTabbedPane();
              return jTabbedPane2;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        BaseMain thisClass = new BaseMain();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getJPanel(), BorderLayout.SOUTH);
              return jContentPane;
    }

    hey gabi,
    i tried your code and it works just fine.... there is no shrinking or any resizing problem?! i don't know... maybe i just don't get it? so maybe u could describe your problem a little more?!
    :)

  • Resize Jtable in panel (using setPreferredScrollableViewportSize)

    Hi,
    I have a JPanel which I've added a JTable. I have set it up with
                   table.setPreferredScrollableViewportSize(new Dimension(900,450));
    On the click of a button I want to call
                   table.setPreferredScrollableViewportSize(new Dimension(900,100));
    validate();
    But the validate doesn't seem to work ?
    Basically the idea is that I shrink the table and put another edit panel below the table for the selected row of the table.
    Any ideas ? Is setPreferredScrollableViewportSize the correct way to resize the JTable ?
    Mark.

    Sorry I figured it out.
    My table was in a panel, I resized the table but not the panel.
    by changing the preferredsize of the panel I got the effect I was looking for.

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

    Hello
    I have a little GUI problem. I created a dialog with a JTabbedPane in the center that contains some JPanel with labels, fields etc. (nothing heavy). The Dialog has a size about 100px*200px.
    Now I put a JTable (with no sizing information) in a JScrollPane and add it to the JTabbedPane and the Dialog gets a size of about 200px*200px.
    Why? I tried a lot, but nothing helped?
    Thankful for every help.

    Oh sorry,
    I want that the JTable (and the JScrollPane) adopts the size of the Dialog (before I added the table). I don't set any size in my code for the dialog and the panels. I set only size for some JFields in the panels and pack() the dialog.
    First everything is wonderfull aligned, but when I add the scrollpane with the table the whole dialog becomes wider.
    Is there a chance that the new tab gets the old size?

  • Resize JTable caused ArrayIndexOutOfBoundsException

    I have called setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN) for my JTable. If I resize the right bound of the last column, I received the following exception. Does anyone know if it is my problem? Thanks!
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 5 >= 5
    at java.util.Vector.elementAt(Vector.java:412)
    at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColum
    nModel.java:271)
    at javax.swing.JTable.accommodateDelta(JTable.java:2185)
    at javax.swing.JTable.columnMarginChanged(JTable.java:2904)
    at javax.swing.table.DefaultTableColumnModel.fireColumnMarginChanged(Def
    aultTableColumnModel.java:576)
    at javax.swing.table.DefaultTableColumnModel.propertyChange(DefaultTable
    ColumnModel.java:615)
    at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Swing
    PropertyChangeSupport.java:156)
    at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Swing
    PropertyChangeSupport.java:125)
    at javax.swing.table.TableColumn.firePropertyChange(TableColumn.java:237
    at javax.swing.table.TableColumn.firePropertyChange(TableColumn.java:243
    at javax.swing.table.TableColumn.setWidth(TableColumn.java:470)
    at javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler.mouseDrag
    ged(BasicTableHeaderUI.java:128)
    at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:25
    5)
    at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:25
    5)
    at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:25
    5)
    at java.awt.Component.processMouseMotionEvent(Component.java:3754)
    at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2294)
    at java.awt.Component.processEvent(Component.java:3543)
    at java.awt.Container.processEvent(Container.java:1159)
    at java.awt.Component.dispatchEventImpl(Component.java:2588)
    at java.awt.Container.dispatchEventImpl(Container.java:1208)
    at java.awt.Component.dispatchEvent(Component.java:2492)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2446
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2200)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2120)
    at java.awt.Container.dispatchEventImpl(Container.java:1195)
    at java.awt.Window.dispatchEventImpl(Window.java:921)
    at java.awt.Component.dispatchEvent(Component.java:2492)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:334)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:126)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:93)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:88)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:80)

    The only thing I can think is that because there is no "NEXT COLUMN" to the one you are trying to resize it throws the ArrayIndexOutOfBoundsException. If you have 4 columns and you tell it to resize next column, and then you try to resize the right side of the 4 column it is trying to resize the next column, column 5, which does not exist and therefore throws the exception.

  • Resize JTable columns by double-clicking header

    I want to implement column resizing in a JTable so that when the user double clicks on the column header with the mouse in the "resize zone" the column automatically adjusts to the width of the longest text in the column. this is how many applications behave (e.g. windows explorer) but I don't think I've ever seen a swing app that does this. I've looked in the API docs for JTable and JTableHeader and I can't see any way of finding out if the mouse is over the edge of a column header. does anyone know of a way to do this?

    Is this laf independant?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
                {"R2-C1","R2-C2","R2-C3"},
                {"R3-C1","R3-C2","R3-C3"}};
        JTable jt = new JTable(data, head);
        JScrollPane jsp = new JScrollPane(jt);
        content.add(jsp, BorderLayout.CENTER);
        JTableHeader jth = jt.getTableHeader();
        jth.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            JTableHeader jth = (JTableHeader)me.getSource();
            int col = jth.columnAtPoint(me.getPoint());
            Rectangle r = jth.getHeaderRect(col);
            if (jth.getCursor().equals(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR))) {
              System.out.println("Cursor, col="+col);
        setSize(300, 300);
        setVisible(true);
      public static void main(String args[]) { new Test(); }
    }

  • Resize jtable column width

    I am trying implement a utility in JTable by which when a person clicks on the column header, the whole column should resize according to the cell which has lengthiest data. If you have seen this in MS Excel where by clicking on the column this happens. I want the same thing.
    Is there anyway already defined in javax.swing?
    I have added a Mouselistener on Tableheader and when the person clicks on a column header, I first finds out the column index. Now on that column index scan the whole column for the lengthiest data. After finding the lengthiest data I set the preferred width for that column and call doLayout on the table object. In this case the problem is of font as the font is not fixed width. The multiplication factor which returns the pixel doesn't gives the right pixel width. Is there any way by which I can find pixel width of a String?

    Use the following code to compute the width of a
    column in pixels required to display the maximum sized
    string in the table column:
    FontMetrics fm =
    table.getFontMetrics(table.getFont());
    int width =
    SwingUtilities.computeStringWidth(fm,maxSizeString)
    //then to set the width of your column:
    TableColumnModel columnModel =
    table.getColumnModel();
    TableColumn column =
    columnModel.getColumn(YOUR_COLUMN);
    column.setPreferredWidth(width);Rizwanthx that was usefull

  • Ctrl PgUp / CtrlPgDown in JTables vs JTabbedPanes

    Hi there, another wee JTable problem.
    I want Ctrl PageUp and Ctrl PageDown to move between JTabbedPanes. This normally works, except when the focus is currently in a JTable. I want it to also work if the focus is in a JTable.
    I have tried to stop the JTable from handling the keys by setting the inputmap to "none" but this has no effect (you can see my code for this below).
    Here is a test program that shows the bad behaviourimport java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class TestTable extends JTable {
         public TestTable(Object[][] data, Object[] headings) {
              super(data, headings);
              setFocusTraversalPolicyProvider(true);
              // Turn off Ctrl PgUp and Ctrl PgDown handling so tab navigation works.
              InputMap inputs = getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              KeyStroke ctrlPgUpKey = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_DOWN_MASK);
              inputs.put(ctrlPgUpKey, "None");
              KeyStroke ctrlPgDownKey = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_DOWN_MASK);
              inputs.put(ctrlPgDownKey, "None");
         public boolean isCellEditable(int row, int column) {
              return false;
         public static void main(String[] args) {
              JFrame frame = new JFrame("Test table");
              JTabbedPane pane = new JTabbedPane();
              frame.add(pane);
              JPanel panel = new JPanel();
              JTextField field = new JTextField("Key Ctrl PgDown or Ctrl PgUp");
              panel.add(field);
              pane.add("test1", panel);
              pane.add("test2", new JScrollPane(new TestTable(new String[][] {{"hello", "me"}}, new String[]{"H1", "H2"})));
              pane.add("test3", new JPanel());
              frame.setBounds(100, 100, 300, 300);
              frame.setVisible(true);
    }Thanks,
    Tim

    i had a similiar problem, had some UIs that had a Tabbed pane and
    ScrollBars, and some tabs had JTables in them, anyhow, I just wanted
    Control-Page_up/Down to work for the JTabbedPane all the the time so
    I did this in my windows look and feel applications and all was well, just posting so maybe this will help someone down the road
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    UIDefaults uiDefaults = UIManager.getDefaults();
    // ginny wants Control-Page-Up and Control-Page-Down to work for tabbed
    // panes, which it does by default, however, it also works for JTable
    // and JScrollPane, and those components grab the keystroke 1st if they are
    // all in the same screen, so disabling it for JTable and JScrollPane
    // see WindowsLookAndFeel.java
    uiDefaults.remove("ScrollPane.ancestorInputMap");
    uiDefaults.put("ScrollPane.ancestorInputMap",
    new UIDefaults.LazyInputMap(new Object[] {
    "RIGHT", "unitScrollRight",
    "KP_RIGHT", "unitScrollRight",
    "DOWN", "unitScrollDown",
    "KP_DOWN", "unitScrollDown",
    "LEFT", "unitScrollLeft",
    "KP_LEFT", "unitScrollLeft",
    "UP", "unitScrollUp",
    "KP_UP", "unitScrollUp",
    "PAGE_UP", "scrollUp",
    "PAGE_DOWN", "scrollDown",
    "ctrl PAGE_UP", "None", //"scrollLeft",
    "ctrl PAGE_DOWN", "None",//"scrollRight",
    "ctrl HOME", "scrollHome",
    "ctrl END", "scrollEnd"
    uiDefaults.remove("Table.ancestorInputMap");
    uiDefaults.put("Table.ancestorInputMap",
    new UIDefaults.LazyInputMap(new Object[] {
    "ctrl C", "copy",
    "ctrl V", "paste",
    "ctrl X", "cut",
    "COPY", "copy",
    "PASTE", "paste",
    "CUT", "cut",
    "RIGHT", "selectNextColumn",
    "KP_RIGHT", "selectNextColumn",
    "LEFT", "selectPreviousColumn",
    "KP_LEFT", "selectPreviousColumn",
    "DOWN", "selectNextRow",
    "KP_DOWN", "selectNextRow",
    "UP", "selectPreviousRow",
    "KP_UP", "selectPreviousRow",
    "shift RIGHT", "selectNextColumnExtendSelection",
    "shift KP_RIGHT", "selectNextColumnExtendSelection",
    "shift LEFT", "selectPreviousColumnExtendSelection",
    "shift KP_LEFT", "selectPreviousColumnExtendSelection",
    "shift DOWN", "selectNextRowExtendSelection",
    "shift KP_DOWN", "selectNextRowExtendSelection",
    "shift UP", "selectPreviousRowExtendSelection",
    "shift KP_UP", "selectPreviousRowExtendSelection",
    "PAGE_UP", "scrollUpChangeSelection",
    "PAGE_DOWN", "scrollDownChangeSelection",
    "HOME", "selectFirstColumn",
    "END", "selectLastColumn",
    "shift PAGE_UP", "scrollUpExtendSelection",
    "shift PAGE_DOWN", "scrollDownExtendSelection",
    "shift HOME", "selectFirstColumnExtendSelection",
    "shift END", "selectLastColumnExtendSelection",
    "ctrl PAGE_UP", "None", //"scrollLeftChangeSelection",
    "ctrl PAGE_DOWN", "None", //"scrollRightChangeSelection",
    "ctrl HOME", "selectFirstRow",
    "ctrl END", "selectLastRow",
    "ctrl shift PAGE_UP", "scrollRightExtendSelection",
    "ctrl shift PAGE_DOWN", "scrollLeftExtendSelection",
    "ctrl shift HOME", "selectFirstRowExtendSelection",
    "ctrl shift END", "selectLastRowExtendSelection",
    "TAB", "selectNextColumnCell",
    "shift TAB", "selectPreviousColumnCell",
    "ENTER", "selectNextRowCell",
    "shift ENTER", "selectPreviousRowCell",
    "ctrl A", "selectAll",
    "ESCAPE", "cancel",
    "F2", "startEditing"
    }));

  • User cannot resize jTables� columns

    Hello,
    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    JScrollpane.
    My problem is that the user cannot resize the jTables� columns.
    Maximum details:
    1.     jtablewidth is set to a fixed value according to internal data:
    JTable1.setPreferredSize( new Dimension(tableWidth, i_TableHeight));
    2.     columnwidth is set according to internal data:
    Col = JTable1.getColumnModel().getColumn(i);
    Col.setWidth(width);
    Col.setResizable(true);
    Col.setMinWidth(width);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    anHeader.setReorderingAllowed(false);
    anHeader.setResizingAllowed(true);
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
         JTable1.setColumnSelectionAllowed(true);
         JTable1.setDragEnabled(true);
         JTable1.setPreferredScrollableViewportSize(new
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
         JTable1.setRequestFocusEnabled(false);
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    412));
         JScrollPane1.setViewportView(JTable1);
         JScrollPane1.setAutoScolls(false);
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,
    Itay

    Columns resizing works by default. You don't need to do anything special.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Resize JTable Columns without Column Header

    Hi all.
    I have a JTable that doesn't display a column header.
    I would like to allow the user to resize the columns by dragging a mouse at the column edges at any point down the table.
    It is not obvious how I can accomplish this.
    Does anyone have any ideas?
    Thanks, Paul.

    That doesn't work, though, since the table has its own listenersIt's not just that. The header's mouse listeners work with instance fields of BasicTableHeaderUI and detection (using e.getPoint) of the header cell and column.
    I would start with copying the entire code of BasicTableHeaderUI to a class of my own, then first eliminate anything that obviously isn't related to column dragging/resizing, then refactor, refactor, refactor to make the listener codes work with a table instead of a header. But like I said, easier said than done, particularly when having to deal with the various JTable column resize modes.
    db

Maybe you are looking for