我试图让JTable在调整包含JTable的窗口时自动调整其大小。
JTable将调整其宽度,如果高度太小而无法全部显示,它右侧还有一个滚动条。
这一个是JFrame,我使用单独的类扩展JPanel:
public class GUIFrame
{
public static void main(String[] args)
{
//Setting up JFrame's basic properties
JFrame mainFrame = new JFrame("Muney Manager");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting up panels:
JPanel mPanel = new JPanel();
mPanel.setLayout(new BoxLayout(mPanel,BoxLayout.PAGE_AXIS));
TablePanel tPanel = new TablePanel();
ToolBar buttonPanel = new ToolBar(tPanel);
mPanel.add(buttonPanel);
mPanel.add(tPanel);
//Setting up Panels and Frame to be displayed :3
mainFrame.getContentPane().add(mPanel);
mainFrame.pack();
mainFrame.setVisible(true);
}
这是包含JTable的那个:
public class TablePanel extends JPanel
{
//DefaultTableModel is needed for adding new rows
private JTable table;
private DefaultTableModel tmodel;
private JScrollPane scrollPane;
//Table's column name
private String[] columnNames = {"Date",
"Category",
"Details",
"Add/Subtract",
"Total"};
Object[][] data = {
{20140925, "Grocery", "Supermarket", -5.23,600.00},
{20141013,"Car Maintenance", "Changing Tires", -200.00, 400.00}
};
public TablePanel()
{
//Initializing tmodel and putting it into table
//It's needed for "adding rows" method
tmodel = new DefaultTableModel(data, columnNames);
table = new JTable();
table.setModel(tmodel);
//Setting up JScrollPane, table Headder
//and make scrollPane visible
table.setFillsViewportHeight(true);
add(new JScrollPane(table));
}
出于某种原因,我无法使用它,我的代码出了什么问题? JTable宽度没有调整大小,我似乎无法在右侧获得滚动条
答案 0 :(得分:1)
考虑使用BorderLayout
而不是......
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame mainFrame = new JFrame("Muney Manager");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting up panels:
JPanel mPanel = new JPanel();
mPanel.setLayout(new BorderLayout());
TablePanel tPanel = new TablePanel();
ToolBar buttonPanel = new ToolBar(tPanel);
mPanel.add(buttonPanel, BorderLayout.NORTH);
mPanel.add(tPanel);
//Setting up Panels and Frame to be displayed :3
mainFrame.getContentPane().add(mPanel);
mainFrame.pack();
mainFrame.setVisible(true);
}
});
}
或者如果你想要更多控制,甚至可能是GridBagLayout
<强>更新强>
JPanel
默认使用FlowLayout
,尝试更改TablePanel
以使用BorderLayout
...
public TablePanel()
{
setLayout(new BorderLayout());
//Initializing tmodel and putting it into table
//It's needed for "adding rows" method
tmodel = new DefaultTableModel(data, columnNames);
table = new JTable();
table.setModel(tmodel);
//Setting up JScrollPane, table Headder
//and make scrollPane visible
table.setFillsViewportHeight(true);
add(new JScrollPane(table));
}