【发布时间】:2020-12-16 07:11:56
【问题描述】:
我的程序中有一个错误示例。我创建了 4 个按钮:1、2、3、4。按钮 2 与按钮 4 重叠,我只是为 2 和 4 添加了事件。
如果我 单击按钮 2,它将被隐藏,而按钮 4 将被显示。 如果我单击 Button 4,将显示 Button 2,而 Button 4 将再次被 Button 2 覆盖。好像发生了什么,但是,当 完成上述操作后,我单击按钮 1 或按钮 3,按钮 4 将 显示出来,当我指向它(不是点击)时,它会消失。
public class UI extends JFrame {
public UI(String title) {
Container container = this.getContentPane();
container.setLayout(null);
JButton btn1 = new JButton("1");
btn1.setBounds(10, 10, 50, 50);
btn1.setBackground(Color.RED);
JButton btn2 = new JButton("2");
btn2.setBounds(10, 70, 50, 50);
btn2.setBackground(Color.GREEN);
JButton btn3 = new JButton("3");
btn3.setBounds(10, 130, 50, 50);
btn3.setBackground(Color.BLUE);
JButton btn4 = new JButton("4");
btn4.setBounds(10, 70, 50, 50);
btn4.setBackground(Color.YELLOW);
container.add(btn1);
container.add(btn2);
container.add(btn3);
container.add(btn4);
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btn2.setVisible(false);
}
});
btn4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btn2.setVisible(true);
}
});
this.setSize(400, 500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
【问题讨论】:
-
container.setLayout(null);先解决这个问题。 Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作,在不同的语言环境中使用不同的 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。 -
感谢您的评论,我已经知道了,我只想创建一个固定大小的程序。如果我使用 FlowLayout 或 BorderLayout 或其他东西,我不知道如何创建 2 个按钮重叠。
-
一般提示: 1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 以最小尺寸提供 ASCII 艺术或 GUI 的 预期 布局的简单绘图,如果可调整大小,则具有更大的宽度和高度 - 以显示应如何使用额外空间。 3) 屏幕截图显示一列三个彩色按钮。对于大小相同的单列组件,我会使用
GridLayout。 -
我只想在同一位置显示2个按钮,当我点击按钮1时,按钮2会出现并且按钮1被隐藏
-
"当我点击按钮 1 时,按钮 2 会出现并且按钮 1 被隐藏" 要么使用
CardLayout,如 this answer 所示,要么只有一个单击单个按钮并更改其状态(文本和颜色等)。另见What is the XY problem?
标签: java swing jbutton layout-manager