我设法让单独的图案显示在面板上。但现在我想创建一个 Token 对象(它是矩形内的两条线)。我想在面板中创建 token 。使用 token 参数,我想创建一个将图案包围在其中的矩形。游戏代币将创建图案,图案又将创建特定的图案。在本例中为十字图案。 我究竟做错了什么?这是我初始化的方式吗?
这是我创建的模式
public class CrossPattern extends JPanel{
private Point2D.Double top;
private Point2D.Double bottom;
private Point2D.Double top1;
private Point2D.Double bottom1;
private Line2D.Double line1;
private Line2D.Double line2;
private Rectangle bbox;
public CrossPattern()
{
// correct Cross pattern
top= new Point2D.Double(bbox.getX(),bbox.getY()) ;
bottom= new Point2D.Double(bbox.getX()+bbox.getWidth(),bbox.getY()+bbox.getWidth()); // correct Cross Pattern
top1= new Point2D.Double(bbox.getX()+bbox.getWidth(),bbox.getY()); // Correct cross Patt
bottom1= new Point2D.Double(bbox.getX(),bbox.getY()+bbox.getHeight()); // correct Cross Patt
line1= new Line2D.Double(top,bottom); // correct Cross Patt
line2= new Line2D.Double(top1,bottom1); // Correct cross patt
}
public void draw(Graphics2D g2)
{
g2.draw(this.line1);
g2.draw(this.line2);
}
}
这是将在盒子的尺寸内创建特定图案的图案。
public class Pattern
{
private CrossPattern pattern1;
int type;
Random random = new Random();
public Pattern(Rectangle bbox)
{
int num= 0; //set random num a int value from 0-2
bbox = bbox;
if(num==0)
{
pattern1 = new CrossPattern();
}
这是我的游戏 token ,我将在其中实现位置和大小
public class GameToken implements VisibleShape
{
private boolean visible;
public Rectangle bbox;
private Pattern pattern;
private Color color;
Random random = new Random();
public GameToken(int x, int y, int width, int height)
{
bbox = new Rectangle ( x,y,width,height);
pattern= new Pattern(bbox);
}
这是我将在其中创建 token 的面板
public class GameTokenPanel extends JPanel {
private CrossPattern patternt;
private Rectangle rect;
private GameToken token1;
public GameTokenPanel()
{
token1= new GameToken(50,50,25,25);
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2= (Graphics2D) g;
patternt.draw(g2);
}
}
最佳答案
您的代码在 g2.draw(this.line2);
处生成编译器异常,因为 line2
未定义,并且 NullPointerException
在 g2.draw(this.line1);
因为 line1
(并假设 line2
)未初始化,因为您已经隐藏了变量。 .
private static class CrossPattern {
//...
private Line2D.Double line1;
public CrossPattern() {
// Oh, look, you've redefined `line1` as a local variable!
Line2D.Double line1 = new Line2D.Double(top, bottom); // correct
//...
摆脱 line1
、top
、bottom
、top1
、bottom1 的重新声明
和 line2
...
除非您有特别充分的理由这样做,否则您应该在 GameTokenPanel
中覆盖 paintComponent
而不是 paint
。
您应该重写 GameTokenPanel
的 getPreferredSize
方法并返回首选值,而不是使用 FRAME_WIDTH
和 FRAME_HEIGHT
“查看”您想要的尺寸。目前,您组件的可视区域将为FRAME_WIDTH - 框架装饰水平插入
和FRAME_HEIGHT - 框架装饰垂直插入
,这可能不符合您的期望。
话虽如此,您应该传递 pattern
组件的当前大小,这样它就可以决定如何最好地渲染模式......
关于java - 无法在框架上显示形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955176/