【发布时间】:2016-07-04 16:35:10
【问题描述】:
我想用.setLocation(x, y)设置每个元素的位置
我需要JPanel 中的JScrollPane。但是当我向JPanel 添加组件时,只显示按钮。但不是JLabel。
下面的方法是在JFrame构造函数中调用:
private void initGUI_test() {
this.setSize(950, 700);
this.setResizable(false);
this.getContentPane().setLayout(null);
JScrollPane mainScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JPanel container = new JPanel();
mainScroll.setSize(900,500);
mainScroll.setLocation(0,100);
mainScroll.setBorder(BorderFactory.createLineBorder(Color.blue));
mainScroll.add(container);
container.setLayout(null);
container.setLocation(0, 0);
container.setSize(900, 500);
JLabel rowA = new JLabel();
rowA.setSize(180, 26);
rowA.setLocation(10, 100);
rowA.setText("Row A");
JButton loadButton = new JButton();
loadButton.setSize(180, 34);
loadButton.setLocation(290, 110);
loadButton.setText("Load file");
container.add(rowA);
container.add(loadButton);
this.getContentPane().add(mainScroll);
}
【问题讨论】:
-
不要使用
null layout! Swing 被设计用于不同的平台、屏幕分辨率、像素完美的 GUI 真的很难维护,相反你应该使用布局管理器或 combinations of them 和 space between components 的空白边框。 -
请参阅Null layout is evil 和Why is it frowned upon to use a null layout in swing,了解有关为什么不应该使用它的更多信息。阅读完以上链接后,请发布minimal reproducible example,我们可以复制粘贴并查看与您相同的问题。
-
以最小尺寸提供 ASCII 艺术或 GUI 的预期布局的简单绘图,如果可调整大小,则具有更大的宽度和高度。
标签: java swing jpanel jscrollpane null-layout-manager