我有一个示例代码,只是构建一个带有矩形和几个按钮的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();
}
}
}
答案 0 :(得分:2)
这个片段是杀手锏:
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();
}
}
Thread.sleep(240);
repaint();
内拨打paintComponent
,因为这会产生无限循环ran
一次就足够了,不要在paintComponent
中反复重新实例化<{1}} (Component, int)
而不是相反super.paintComponent
时,请不要忘记paintComponent
。每当你需要再次绘制一个组件时(也就是说,你想要调用paintComponent
()),在该组件上调用repaint()
。