形状绘图GUI。将paintComponent与从JPanel派生的类一起使用。

时间:2012-10-17 19:15:10

标签: user-interface graphics paintcomponent

我正在尝试绘制一个简单的gui,用户在其中添加数据,然后按下按钮,它会在窗口中绘制形状。我在较大的节目上失败了,所以我回到原点。我只是想创建一个简单的窗口,在菜单栏中有一个“绘图”按钮。按下按钮时,我已经硬编码到实现图形类的JPanel派生的类中的形状应该出现在同一个窗口中。

这就是我所拥有的,但它不起作用。有人可以看看我做错了什么。令人沮丧的是,当我只是创建形状并将其添加到构造函数中的布局时,它工作正常,但当我尝试使用按钮执行操作时,它会失败。

感谢。

公共类ShapeGUITest扩展了JFrame {

public static final int WINDOW_WIDTH = 500;
public static final int WINDOW_HEIGHT = 500;
public static final int X = 100;
public static final int Y = 75;
public static final int SHAPE_BASE = 200;
public static final int SHAPE_HEIGHT = 250;
JPanel buttonPanel;
JComponent shapeArea;

public ShapeGUITest() {

    super("Draw Shapes Dammit!");
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    shapeArea = new Jpanel();
    add(shapeArea, BorderLayout.CENTER);

    JButton drawButton = new JButton("Draw");
    drawButton.addActionListener(new DrawButtonListener());

    JMenuBar bar = new JMenuBar();
    bar.add(drawButton);
    setJMenuBar(bar);

}

/*public void drawShapePanel() {
    shapeArea = new ShapePanel();
    add(shapeArea, BorderLayout.CENTER);
}*/

private class DrawButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
    //drawShapePanel();

    //shapeArea = new ShapePanel();
    //add(shapeArea, BorderLayout.CENTER);
    ShapePanel s = new ShapePanel();
    //s.setVisible(true);
    //shapeArea.removeAll();
    shapeArea.add(s);
    shapeArea.revalidate();
    validate();
    //ShapeFrame s = new ShapeFrame();

}
}

private class ShapeFrame extends JFrame {

    public ShapeFrame() {
        super("the shape is here");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        super.paint(g);
        setBackground(Color.WHITE);
        g.setColor(Color.YELLOW);
        g.fillRect(X, Y, SHAPE_BASE, SHAPE_HEIGHT);
        g.setColor(Color.GREEN);
        g.drawRect(X, Y, SHAPE_BASE, SHAPE_HEIGHT);
    }
}

private class ShapePanel extends JPanel {

    public ShapePanel() {
        super();
        setVisible(true);
        setLayout(new FlowLayout());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(Color.WHITE);
        g.setColor(Color.YELLOW);
        g.fillRect(X, Y, SHAPE_BASE, SHAPE_HEIGHT);
        g.setColor(Color.GREEN);
        g.drawRect(X, Y, SHAPE_BASE, SHAPE_HEIGHT);
    }
}

public static void main(String[] args) {
    ShapeGUITest gui = new ShapeGUITest();
    gui.setVisible(true);
}

}

0 个答案:

没有答案