我正在尝试制作一个程序,其中我在JFrame中有两个JPanel,其中一个包含画布。我试图找到一种方法来让画布不断更新,这样我就可以在画布中创建类似游戏的东西。我想知道我是如何做到的,以便带有画布的JPanel不断刷新,以便你可以看到画布中的某些内容发生了变化。这是我的代码:
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main
{
private JFrame frame;
private JPanel mainPanel;
private JPanel gamePanel;
private JPanel sidePanel;
public void setup()
{
frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocation(100, 50);
mainPanel = new JPanel();
Dimension d = new Dimension(800, 600);
mainPanel.setMaximumSize(d);
mainPanel.setMinimumSize(d);
mainPanel.setPreferredSize(d);
frame.add(mainPanel);
frame.pack();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
}
public void setupPanels()
{
gamePanel = new JPanel();
Dimension d = new Dimension(600, 600);
gamePanel.setMaximumSize(d);
gamePanel.setMinimumSize(d);
gamePanel.setPreferredSize(d);
gamePanel.setBackground(Color.RED);
mainPanel.add(gamePanel);
sidePanel = new JPanel();
d = new Dimension(600, 600);
sidePanel.setMaximumSize(d);
sidePanel.setMinimumSize(d);
sidePanel.setPreferredSize(d);
sidePanel.setBackground(Color.BLUE);
mainPanel.add(sidePanel);
}
public void setupGame()
{
GameArea game = new GameArea();
gamePanel.add(game);
game.start();
}
public static void main(String[] args)
{
Main main = new Main();
main.setup();
main.setupPanels();
main.setupGame();
}