【问题标题】:Java : need explanation about GraphicsJava:需要关于图形的解释
【发布时间】:2013-01-23 08:16:20
【问题描述】:

我想了解更多有关图形以及如何使用它的信息。

我有这门课:

public class Rectangle 
{
    private int x, y, length, width;
    // constructor, getters and setters

    public void drawItself(Graphics g)
    {
        g.drawRect(x, y, length, width);
    }
}

还有一个非常简单的框架:

public class LittleFrame extends JFrame 
{
    Rectangle rec = new Rectangle(30,30,200,100);      

    public LittleFrame()
    {
        this.getContentPane().setBackground(Color.LIGHT_GRAY);
        this.setSize(600,400);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args)
    {
        new LittleFrame();
    }
}

我只想将这个矩形添加到我的 LittleFrame 的容器中。但我不知道该怎么做。

【问题讨论】:

标签: java swing graphics


【解决方案1】:

我建议您创建一个扩展 JPanel 的额外类,如下所示:

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

public class GraphicsPanel extends JPanel {

    private List<Rectangle> rectangles = new ArrayList<Rectangle>();

    public void addRectangle(Rectangle rectangle) {
        rectangles.add(rectangle);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Rectangle rectangle : rectangles) {
            rectangle.drawItself(g);
        }
    }
}

然后,在您的 LittleFrame 类中,您需要将此新面板添加到框架内容窗格中,并将您的 Rectangle 添加到要绘制的矩形列表中。在LittleFrame构造函数的最后,添加:

GraphicsPanel panel = new GraphicsPanel();
panel.addRectangle(rec);
getContentPane().add(panel);

【讨论】:

  • @Rob 另一种选择是用您设置“背景颜色”的JPanel 替换您的Rectangle 类,然后将这些JPanel 添加到您的LittleFrame。对于JPanel 的定位和大小,请使用适当的LayoutManager。这个解决方案更多的是“摇摆”方式
  • 除非他接下来要画圆圈。
猜你喜欢
  • 2019-11-08
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多