【发布时间】:2015-08-30 11:17:04
【问题描述】:
我正在使用扩展Canvas 的类来尝试制作康威的生命游戏副本。我对 Java 并不陌生,但我对 Swing 和画布都很陌生。我尝试了许多将JButton 对象添加到我的画布的方法,但都没有成功。我已经包含了我的代码,如果有人对我如何实现按钮有任何建议,将不胜感激。
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ConwaysGameOfLife extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int SIZE = 960;
public static final String TITLE = "Conway's Game of Life";
private boolean running = false;
private Thread thread;
private static JButton but;
public static void main(String[] args)
{
ConwaysGameOfLife game = new ConwaysGameOfLife();
game.setPreferredSize(new Dimension(SIZE-10, SIZE-10));
game.setMaximumSize(new Dimension(SIZE-10, SIZE-10));
game.setMinimumSize(new Dimension(SIZE-10, SIZE-10));
JFrame frame = new JFrame(TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
but = new JButton("Button");
frame.add(but);
game.start();
}
private void start()
{
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private void stop()
{
if(!running)
return;
try{thread.join();}
catch(InterruptedException e){}
System.exit(1);
}
public void run()
{
while(running)
{
System.out.println("RUNNING");
}
stop();
}
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0,0,SIZE,64);
for(int i = 16; i < SIZE; i += 16)
{
g.drawLine(i,0,i,SIZE);
g.drawLine(0,i,SIZE,i);
}
}
}
【问题讨论】:
-
一般不会,但是在不调用
super.paint的情况下覆盖paint并没有帮助 -
你能具体说明你面临的问题吗
标签: java swing canvas awt jbutton