I'm using a JTable and adding it to a panel which uses a gridbaglayout like so:
JTable qdbs = new JTable(rowData, columnNamesVector);
qdbs.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
panel.add(qdbs, c);
I don't want the table to be in a scroll pane, but I do want the table to take up the entire width of the panel. How would I accomplish this?
An SSCCE as requested:
import javax.swing.*;
import java.awt.*;
public class Main{
public static void main(Stri开发者_运维百科ng[] args) {
new TestFrame();
}
public static class TestFrame extends JFrame{
public TestFrame() {
this.setTitle("SSCCE");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
JTable testTable = new JTable(10,2);
panel.add(testTable, c);
this.add(panel);
this.pack();
this.setVisible(true);
}
}
}
I would like this table to always take up the entire width of the panel (except the insets). Currently the table does not change size when the frame is resized.
You need to add constrains to tell the layout what to do with more space. In your SSCCE add these items:
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 0;
import java.awt.*;
import javax.swing.*;
public class Test
{
public static void main(String args[]) throws Exception
{
JPanel panel = new JPanel( new GridBagLayout() );
JTable table = new JTable(5, 5);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(table, gbc);
JFrame frame = new JFrame();
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
If you need more help post a SSCCE that demonstrates the problem.
c
is a GridBagConstraint
or something along those lines, I imagine? The very simplest thing to do would be to set the LayoutManager
of the JPanel
to a BorderLayout
, then just add with the constraint BorderLayout.CENTER
.
hmmm
Alex Bliskovsky wrote panel.add(qdbs, c);
that's wrong, not, never do that, you are forgot wrap you JTable to the ScrollPane and then you can play with some of LayoutManagers, for related examples for LayoutManagers check GridBagConstraints for GrigBagLayout
The following frame will correctly resize the table when the frame is resized.
public class Sandbox {
public static void main(String[] args) {
new TestFrame();
}
public static class TestFrame extends JFrame {
public TestFrame() {
this.setTitle("SSCCE");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
JTable testTable = new JTable(10, 2);
panel.add(testTable, c);
this.add(panel);
this.pack();
this.setVisible(true);
}
}
}
Perhaps with:
GridBagConstraints.fill = GridBagContraints.BOTH;
精彩评论