我有一个createUI()函数,可以将JPanel加载到NORTH,SOUTH,EAST。
private void createUI() {
add(createToolBar(), BorderLayout.NORTH);
add(createDataView(), BorderLayout.SOUTH);
add(createHistoryView(), BorderLayout.EAST);
createMenuBar();
setTitle("My Application");
}
每个组件都显示在正确的位置,但是,它们都是固定大小的JPanel。我想知道JPanel是否可以完全填充BorderLayout区域。
例如,createDataView()是一个带表的简单Jpanel。我希望它能够水平扩展,并且具有固定的高度。
private JPanel createDataView(){
JPanel panel = new JPanel();
String data[][] = {{"001","vinod","Bihar","India","Biology","65","First"},
{"002","Raju","ABC","Kanada","Geography","58","second"},
{"003","Aman","Delhi","India","computer","98","Dictontion"},
{"004","Ranjan","Bangloor","India","chemestry","90","Dictontion"},
{"004","Ranjan","Bangloor","India","chemestry","90","Dictontion"}};
String col[] = {"Roll","Name","State","country","Math","Marks","Grade"};
JTable table = new JTable(data,col);
table.setPreferredScrollableViewportSize(new Dimension(900,100));
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
JScrollPane pane = new JScrollPane(table);
table.setAutoResizeMode(JTable.WIDTH);
table.doLayout();
panel.add(pane);
return panel;
}
现在我依靠手动设置尺寸。但是,我想获得当前窗口宽度,并将其设置如下。
table.setPreferredScrollableViewportSize(new Dimension(900,100));
答案 0 :(得分:1)
新JPanel
的默认布局为FlowLayout
; GridLayout
可能是数据视图的替代方案。您可以比较A Visual Guide to Layout Managers中的可能性。
JPanel panel = new JPanel(new GridLayout(1, 0));
附录:你的setAutoResizeMode()
看起来很可疑; JTable.WIDTH
不可能只是巧合的有效值。 GridLayout
适用于默认值JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS
,但您可以尝试使用其他设置。
table.setAutoResizeMode(JTable.WIDTH);
答案 1 :(得分:1)
使用borderlayout,NORTH,SOUTH,EAST和WEST边框都采用包含面板的默认大小,但CENTER会扩展到占用所有剩余空间。我建议将createDataView放在布局的这一部分。