编辑:当我启动程序时,棋盘会按预期绘制,并且按钮起作用。但我希望只有在按下按钮时才绘制棋盘,而不是在运行程序时绘制。我怎样才能做到这一点 ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Male extends JFrame implements ActionListener {
JFrame frame;
JPanel DrawPanel;
JButton button;
public void Male() {
frame = new JFrame();
button = new JButton("MALE");
button.addActionListener(this);
MyDrawPanel DrawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, DrawPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setSize(500,500);
frame.setVisible(true);
}
public static void main(String[] args) {
Male gui = new Male();
gui.Male();
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
setBackground(Color.WHITE);
int x=0;
int y=0;
for (int i=0; i<32; i++){
g.fillRect(x, y, 50, 50);
x = x + 100;
if (x == 400){
x = 50;
y = y + 50;
}else if (x == 450){
x = 0;
y = y + 50;
}
}
}
}