我有一个示例代码,它只是用一个矩形和几个按钮构建一个 JFrame。我完成了矩形的构建,现在我要放置两个按钮,一个开始 - 顶部,一个停止 - 底部。
我有一切工作,至少它的科学。但是,当我尝试设置开始按钮来运行代码时,什么也没有发生。我试图通过创建一个JFrame来查看是否有错误并且代码是成功的。JFrame 应该使用启动按钮打开,paintComponent()
而停止则终止整个事情。
有没有人可以提供一些指导,我已经好几天没睡了,试图弄清楚这一点。
public static void main (String[] args){
TwoButtonsRandomRec two = new TwoButtonsRandomRec();
two.go();
}
public void go(){
JPanel pan = new JPanel(new GridBagLayout());
START = new JButton("START");
START.addActionListener(new StartListener());
STOP = new JButton("STOP");
STOP.addActionListener(new StopListener());
pan.add(START);
pan.add(STOP);
frame = new JFrame();
frame.getContentPane().add(BorderLayout.NORTH, START);
frame.getContentPane().add(BorderLayout.SOUTH, STOP);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void GUI(){
JFrame frame2 = new JFrame();
frame2.setSize(500,500);
frame2.setVisible(true);
}
class StartListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//frame.getContentPane().add(new DrawPanel());
//System.exit(0);
//
DrawPanel panel = new DrawPanel();
}
}
class StopListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
/*
* Panel created
* rectangle drawn to random sizes
*/
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
ran = new Random();
g.setColor(new Color(ran.nextInt(255),+
ran.nextInt(255),ran.nextInt(255)));
height = ran.nextInt(getHeight());
width = ran.nextInt(getWidth());
x = ran.nextInt(getWidth()-width);
y = ran.nextInt(getHeight()-height);
g.fillRect(x,y,width,height);
//repaint();
try{
Thread.sleep(240);
}catch(InterruptedException ie){
}
repaint();
}
}
}