The*_*eIt 0 java swing jframe paintcomponent
我是Java GUI的新手,我试图让这个程序在点击按钮时显示一个方块.没有任何反应,因为repaint()不适用于paintComponent(Graphics g).我搜索过,有些人说使用事件调度线程,但我仍然很困惑
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Ham extends JFrame implements ActionListener
{
JPanel p1;
JButton b1;
public Ham(){
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
b1 = new JButton("Check");
b1.addActionListener(this);
p1.add(b1);
add(p1, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == b1){
repaint();
}
}
public void paintComponent(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(100,100,50,50);
}
}
Run Code Online (Sandbox Code Playgroud)