我有一个示例代码,它只是构建一个带有矩形和几个按钮的 JFrame。我完成了矩形的构建,现在我要放置两个按钮,一个开始 - 顶部,一个停止 - 底部。
我一切都正常,至少是它的科学性。但是,当我尝试设置开始按钮来运行代码时,什么也没有发生。我尝试通过创建JFrame来查看是否有错误,并且代码成功。 JFrame 应该通过一个启动按钮打开,该按钮启动 paintComponent()
,而停止则终止整个事情。
有没有人可以提供一些指导,我已经好几天没有 sleep 试图解决这个问题了。
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();
}
}
}
最佳答案
这个片段是一个 killer :
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
中一遍又一遍地重新实例化它。 - 将组件添加到框架的方式不正确
(Component, int)
而不是相反 - 使用 Java 编码约定,即变量和方法采用驼峰式命名并以小写字母开头。
- 如果您已经将按钮添加到面板中,则只需将该面板添加到框架中,而不需要添加按钮。否则就意味着你的面板毫无用处。
- 别忘了
super.paintComponent
当您覆盖paintComponent
时.
每当您需要再次绘制组件时(即,您希望以某种方式调用 paintComponent
()),请调用 repaint()
在该组件上。
关于java - 从内部类调用paint方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339964/