2

我正在尝试绘制一个简单的 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);
}

}

4

0 回答 0