【发布时间】:2020-08-03 03:10:59
【问题描述】:
我在一个简单的(?)概念上遇到了一个非常令人困惑的问题。我正在尝试学习JFrame、JPanel 等的基础知识,现在正在尝试实现一个简单的任务。我想有一个大的JFrame,叫做画布,里面有两个JPanel,彼此相邻,没有边距或任何东西。在这两个 JPanel 中,我有一个按钮覆盖了一个彩色矩形。当您单击按钮时,按钮应该消失并显示颜色。我的问题很多。
代码似乎有自己的生命。即使在 print 语句中使用 get 消息也会导致输出发生变化。至于输出本身,乍一看,它看起来不错,两个按钮并排命名正确。
但是,当您单击按钮 1 时,两个按钮都会消失,而第三个按钮(名为按钮 2)会出现在右上角。当您单击新按钮时,它会禁用但不会消失。
有时当你点击按钮 1 时,第三个按钮 2 也会出现,但原来的按钮 2 只禁用不隐藏。此外,整个背景是蓝色的,而不是应有的红色和蓝色。当您单击按钮 2 时会发生一组全新的事件,但希望这可能足以帮助您。
非常感谢!
import java.awt.*;
import javax.swing.*;
public class testbig {
public static void main(String[] args) {
JFrame canvas = new JFrame("canvas");
canvas.setSize(400,400);
canvas.setVisible(true);
canvas.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
canvas.setLayout(null);
testinner temp = new testinner("1",Color.blue);
temp.setBounds(0,0,200,400);
canvas.getContentPane().add(temp);
testinner temp2=new testinner("2",Color.red);
temp2.setBounds(200,0,200,400);
canvas.getContentPane().add(temp2);
}
}
public class testinner extends JPanel implements ActionListener{
private JButton button;
private Color color2;
public testinner(String title,Color color) {
super();
color2=color;
setSize(200,400);
setBackground(color);
setLayout(new FlowLayout());
button=new JButton(title);
button.setBounds(getX(), getY(), getWidth(), getHeight());
button.setVisible(true);
button.addActionListener(this);
//panel.add(label);
add(button);
}
public void paintComponent(Graphics gr) {
gr.setColor(color2);
gr.fillRect(getX(), getY(), getWidth(), getHeight());
}
public void actionPerformed( ActionEvent evt){
button.setEnabled(false);
button.setVisible(false);
//System.out.println(this);
//shown.setVisible(true);
}
}
【问题讨论】:
-
您不应该将“getX”添加到您的
fillRect或按钮的setBounds。它们应该是相对于它们所在的容器的值。这也适用于您的paintComponent。
标签: java swing jpanel jbutton actionlistener