【发布时间】:2019-05-09 18:00:19
【问题描述】:
我正在使用 Swing 设计一个 Java 应用程序,但我在设计没有布局的 GUI 时遇到了麻烦。
我的目的是设计一个带有一个JPanel 和四个JButtons 的GUI。我已经计算好在正确的位置设置按钮和面板,并编码如下:
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame {
public MainFrame() {
this.setTitle("Example Frame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
JPanel randomPanel = new JPanel();
randomPanel.setOpaque(true);
randomPanel.setBackground(Color.RED);
randomPanel.setBounds(10, 10, 430, 530);
JButton addButton = new JButton("Add");
addButton.setBounds(10, 550, 100, 40);
addButton.setBackground(Color.GRAY);
JButton deleteButton = new JButton("Delete");
deleteButton.setBounds(120, 550, 100, 40);
deleteButton.setBackground(Color.GRAY);
JButton refreshButton = new JButton("Refresh");
refreshButton.setBounds(230, 550, 100, 40);
refreshButton.setBackground(Color.GRAY);
JButton devButton = new JButton("Developer");
devButton.setBounds(340, 550, 100, 40);
devButton.setBackground(Color.GRAY);
this.add(randomPanel);
this.add(addButton);
this.add(deleteButton);
this.add(refreshButton);
this.add(devButton);
this.setSize(900, 600);
this.setResizable(false);
this.setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
按照代码,组件预计如下放置:
但是,实际的表单显示如下:
组件超出形式,与预期外观不符。
这是什么问题,应该怎么做才能准确放置组件?
【问题讨论】:
-
不做数学计算,我假设您根据 frame 的大小计算大小,并且没有考虑标题栏和边框的大小。一般来说,您应该不使用
setBounds来放置组件。请改用LayoutManager。在这种情况下,您可以拥有一个带有BorderLayout的“主”面板。红色面板可能位于“主”面板的CENTER中。这些按钮可以位于带有GridLayout(1,4)的自己的面板中,而该面板又位于“主”面板的SOUTH中。 -
@Marco13 我也很困惑,如果尺寸对标题栏很重要,所以我截取了表格并在 Photoshop 应用程序上计算了尺寸。首先宽度和高度都不正确,我将宽度调整为 900px,然后高度为 602px。我认为摇摆应用程序本身是不正确的。我会尝试你的解决方案,但我很怀疑,因为我想要精确的尺寸。
-
@cylee 有一些简单的 API 可以解决所有这些问题,从布局管理 API 开始