我正在使用一个类,它扩展了Canvas,试图复制康威的生命游戏。我对Java并不陌生,但我对Swing和canvas都很陌生。我尝试过许多将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);
}
}
}发布于 2015-06-15 04:04:01
当前的问题是,您已经将组件添加到BorderLayout中的相同位置。
frame.add(game); // Look and me, I'm in the CENTER
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
but = new JButton("Button");
frame.add(but); // Look and me, I'm in the CENTER现在,因为在添加按钮之后还没有使框架失效,所以它还没有更新,所以没有显示,但是即使显示了,您可能会发现您有一些奇怪的问题,因为AWT组件没有z深度的概念,这意味着它可能涵盖或不涵盖button...fun内容。
相反,将按钮添加到帧/BorderLayout中的另一个位置
frame.add(game); // Look and me, I'm in the CENTER
but = new JButton("Button");
frame.add(but, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);有关更多细节,请查看如何使用BorderLayout。
我也会小心地打破Canvas的油漆链,而不知道绘画是如何完成的。你应该打电话给super.paint。
实际上,在本例中,使用Canvas (和许多问题)几乎没有好处,相反,您可能应该使用JPanel并覆盖它的paintComponent方法,确保在进行任何自定义绘制之前调用super.paintComponent
有关更多细节,请参见AWT和Swing中的绘画和表演定制绘画
https://stackoverflow.com/questions/30837062
复制相似问题