我对java比较陌生,我只是想编写一个在按下按钮时绘制一个框的GUI。我的问题是,我的程序在按下按钮之前绘制了框,我不知道如何解决这个问题。
这是我的控制器类:
import java.awt.*;
import javax.swing.*;
import java.awt.event.* ;
public class TestController extends JFrame {
private JButton enterButton;
private JPanel buttonHolder;
private Container contentPane;
private TestView view;
public TestController() {
contentPane = getContentPane();
enterButton = new JButton("Enter");
buttonHolder = new JPanel();
buttonHolder.setPreferredSize(new Dimension (600, 100));
contentPane.add(buttonHolder, BorderLayout.SOUTH);
buttonHolder.add(enterButton);
view= new TestView();
view.setPreferredSize(new Dimension (125, 125));
contentPane.add(view, BorderLayout.CENTER);
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
view.repaint();
}
});
}
public static void main(String[] args) {
TestController bc = new TestController() ;
bc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
bc.pack();
bc.setVisible(true) ;
}
}
这是我的视图类:
import java.awt.* ;
import java.awt.geom.*;
import javax.swing.* ;
public class TestView extends JPanel {
public TestView() {}
public void paintComponent( Graphics g ){
super.paintComponent( g );
Graphics2D g2= ( Graphics2D ) g;
Rectangle2D rect= new Rectangle2D.Double(0, 0, 30, 30);
g2.setPaint( Color.CYAN );
g2.fill( rect );
}
}