我已经将 Graphics 2D 实现到 JPanel 中,并让它在上面绘制一个圆圈。但是,我希望稍后能够调用 2D 形状以便能够移动它们。我该怎么做这样的事呢?我尝试将其声明为变量,但我不知道如何,任何帮助都会很棒,谢谢。
package com.aqagame.harrykitchener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game
{
public Game()
{
JFrame window = new JFrame ("Main Game");
JPanel firstPanel = new JPanel(new GridLayout(3, 1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
}
};
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new Game();
}
});
}
}
最佳答案
第一步可以是一个自己的类,负责绘制游戏内容。 (使用匿名内部类解决这个问题的扩展性不太好)。
您想要绘制的形状可以驻留在 List
中,您可以简单地迭代来绘制它们。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game
{
public Game()
{
JFrame window = new JFrame ("Main Game");
JPanel firstPanel = new GamePanel();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new Game();
}
});
}
}
class GamePanel extends JPanel
{
private final List<Shape> shapes = new ArrayList<Shape>();
GamePanel()
{
shapes.add(new Ellipse2D.Double(10,20,30,40));
}
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
for (Shape shape : shapes)
{
g2d.draw(shape);
}
}
}
重要提示:顾名思义,这应该成为一个“游戏”。当您继续这样做时,您很可能会遇到严重困难。 Stackoverflow 不是“答案生成机”,游戏不能通过反复试验来编程,而是涉及一些规划。例如,您现在可以轻松地使用鼠标选取形状(使用 MouseListener 和 shape.contains(mousePosition)
方法),但是拖动它们甚至只是用不同的颜色绘制它们将需要一些更大的基础设施。例如,您应该考虑类似 GameEntity
类,它封装了游戏中出现的实体等。
关于java - 使用变量名称标记形状的 2D 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270342/