Java:关于图形界面的说明

3

我希望了解一些关于图形设计以及如何使用它的知识。

我有这个类:

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容器中。但是我不知道该如何实现。


3
我建议您查看自定义绘图Graphics 2D在AWT和Swing中绘图 - MadProgrammer
1个回答

4

我建议您创建一个额外的类,继承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类中,你需要将这个新的panel添加到你的frame内容面板中,并将你的Rectangle添加到要绘制的矩形列表中。在LittleFrame构造函数的末尾添加:

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

1
@Rob 另一个选项是用 JPanel 替换你的 Rectangle 类,然后在上面设置一个 "backgroundColor",并将这些 JPanel 添加到你的 LittleFrame 中。对于 JPanel 的定位和大小,请使用适当的 LayoutManager。这个解决方案更符合 "Swing" 的方式。 - Guillaume Polet
除非他想要画圆形。 - Dan D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接