1

Hi here are my codes for my table settings:

String [] column = {"MacAddress","PcName","OperatingSystem","IpAddress","Port","Status"};
    model = new DefaultTableModel(0,column.length);
    model.setColumnIdentifiers(column);
    mainTable = new JTable(model);
    mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    for(int i=0;i<=column.length-1;i++){
    mainTable.getColumnModel().getColumn(i).setPreferredWidth(300);
    }
    pane = new JScrollPane(mainTable);
    pnlTabel = new JPanel();
    pnlTabel.setBorder(BorderFactory.createTitledBorder(""));
    pnlTabel.setPreferredSize(new Dimension(dim.width*70/100, dim.height*60/100));
    pnlTabel.add(pane);
addMainPanel(pnlTabel);

Here is my addMainPanel() function:

public void addMainPanel(Component pnl){
    mainPanel.add(pnl);
    mainPanel.revalidate();
}

And here is my code for my mainPanel:

    mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(mainPanel,"Center");

and I'm using border layout for my frame:

setLayout(new BorderLayout(0,0));

My problem is that, even i use this set of code to set my JTable to fit but it seems to fail all the this, this code:

 mainTable.setAutoResizeMode(JTa![enter image description here][1]ble.AUTO_RESIZE_OFF);
for(int i=0;i<=column.length-1;i++){
mainTable.getColumnModel().getColumn(i).setPreferredWidth(300);
}

When is use that code, my jtable does not resize but only add on a horizontal scroll bar at the bottom.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Chris
  • 612
  • 2
  • 9
  • 23
  • the perils of using setXXSize ;-) DONT, ever: after that, a component will NEVER AGAIN try to calculate its sizing hints ... [for details](http://stackoverflow.com/a/7229519/203657) – kleopatra Oct 03 '12 at 10:26

2 Answers2

5

No offense meant but .. your code and consequently your question is a mess ;-) Plus you don't explain what exactly you want to achieve.

Trying to detangle, taking the nested layouts/resizing characteristics (as seen in the snippets, might not be complete):

frame // BorderLayout
   mainPanel // FlowLayout
       pnlTabel  // FlowLayout, hard-coded prefSize
           pane // scrollPane 
               mainTable // auto-resize-off

Aside: intentionally kept untelling names to demonstrate how mixing naming schemes tend to contribute to overall confusion :-) Doesn't really matter whether you decide for pre or postFixing some type-related marker, but if you do be consistent.

In that hierarchy, there are two levels of FlowLayout which basically will layout their children at their respective prefs and adjusting their own pref accordingly, lest the pref were hard-coded on the level of the pnlTable: however the table's pref will be changed (by changing the column prefs) it cannot bubble further up because ... hard-coding the pref leads not calculating its size (neither by layoutManager and nor uiDelegate, both never get a chance to do it)

Another issue - the more interesting one :-) - is that the JScrollPane is somewhat special in

  • calculating its own prefSize from its view's pref/scrollablePrefViewportSize depending on whether or not the view implements Scrollable (JTable does so, though in a crappy way)
  • being a validationRoot: invalidating the view (or any children) doesn't bubble further up the hierarchy

Assuming that you want the table's scrollPane to grow if the prefWidts of the columns change, there are two thingies to tweak:

  • implement table's getPreferredScrollableWidth to return a value calculated based on the prefWidth of the columns
  • revalidate a container higher up in the hierarchy

Some code to play with:

final JTable table = new JTable(50, 10) {
    // properties to base a reasonable prefScrollable size
    int visibleColumns = 3;
    int visibleRows = 10;
    // hard-coded default in super
    Dimension dummySuper = new Dimension(450, 400);
    @Override
    public Dimension getPreferredScrollableViewportSize() {
        Dimension dim =  super.getPreferredScrollableViewportSize();
        if (!dummySuper.equals(dim)) return dim;
        dim = new Dimension();
        for (int column = 0; column < Math.min(visibleColumns, getColumnCount()); column++) {
            dim.width += getColumnModel().getColumn(column).getPreferredWidth();
        }
        dim.height = visibleRows * getRowHeight();
        return dim;
    }

};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < table.getRowCount(); i++) {
    table.setValueAt("row: " + i, i, 0);
}
JComponent tablePanel = new JPanel();
tablePanel.add(new JScrollPane(table));

Action sizeColumns = new AbstractAction("size columns") {
    int prefWidth = 75;
    @Override
    public void actionPerformed(ActionEvent e) {
        int newWidth = prefWidth + 15;
        for (int i = 0; i < table.getColumnCount(); i++) {
            if (table.getColumnModel().getColumn(i).getPreferredWidth() == prefWidth)
                table.getColumnModel().getColumn(i).setPreferredWidth(newWidth);
        }
        prefWidth = newWidth;
        // revalidate "higher up" than the table itself
        frame.revalidate();
    }
};
frame.add(new JButton(sizeColumns), BorderLayout.SOUTH);
kleopatra
  • 51,061
  • 28
  • 99
  • 211
4

If you want a JTable to fill the available space, you should put it inside a JPanel which has a BorderLayout layout manager. Also don't forget about the JScrollPane which ensures that if the table doesn't fit into the view (e.g. too many rows), scrollbars will appear:

JFrame frame = new JFrame();
// set up frame

JTable table = new JTable();
// Set up table, add data

// Frame has a content pane with BorderLayout by default
frame.getContentPane().add( new JScrollPane( table ), BorderLayout.CENTER );

If you have other content you wish to display besides the table, you can add those to the NORTH, SOUTH, EAST, WEST parts of the content panel (which can be wrapped into other panels if more components are to be placed there).

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    that is fine for the width, but if i want my Jtable to fit my scrollpane's height (when there are not enough rows for scroll bar)??? how can i achieve that? thanks – caniaskyouaquestion Jan 28 '15 at 13:46