Java-单击按钮后绘制矩形
这个简单的代码应该在按下按钮后绘制矩形,但它不起作用。我不知道怎么做,我唯一想到的是布尔变量触发器,但它似乎不起作用。有什么建议吗?多谢各位Java-单击按钮后绘制矩形,java,swing,jbutton,actionlistener,Java,Swing,Jbutton,Actionlistener,这个简单的代码应该在按下按钮后绘制矩形,但它不起作用。我不知道怎么做,我唯一想到的是布尔变量触发器,但它似乎不起作用。有什么建议吗?多谢各位 public class testing extends JFrame implements ActionListener{ public JButton button; public boolean check; public void paint(Graphics g){ if(check==true){
public class testing extends JFrame implements ActionListener{
public JButton button;
public boolean check;
public void paint(Graphics g){
if(check==true){
g.setColor(Color.red);
g.fillRect(30, 50, 50, 50);
}
}
public void start(){
setLayout(new BorderLayout());
button=new JButton();
button.setPreferredSize(new Dimension(200,20));
button.setText("ClickMe");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
setSize(500,500);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
check=true;
}
public static void main(String args[]){
testing x=new testing();
x.start();
}
}
您可以在actionPerformed内调用repaint
public void actionPerformed(ActionEvent e) {
check=true;
repaint();
}
您需要在
ActionListener
中调用repaint
。使用paintComponent
而不是paint
进行Swing中的自定义绘制。同时调用super.paintComponent(g)
@ReimeusJFrame
没有paintComponent
方法。我知道,这就是为什么我鼓励OP阅读并找出所需的新类(提示)