首页 > 解决方案 > 对象未出现在 JPanel 上

问题描述

我正在尝试添加一个形状(矩形到 GUI),请告诉我我的代码有什么问题?- 目标是使用按钮添加形状,但在我什至使用 ActionListener 之前,我试图在界面上显示形状。

public class FactoryPattern extends JFrame {
    
    public static void main(String[] args) {

        ShapeFactory shapes = new ShapeFactory();
        JPanel panel = new JPanel();
        
        JButton loadBtn = new JButton("Load Shapes");
        JButton sortBtn = new JButton("Sort Shapes");
        panel.add(sortBtn);
        panel.add(loadBtn);
        panel.add(shapes);

        
        
        JFrame frame = new JFrame("Display two shapes (rectangles)");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(600, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
      } 
}
class ShapeFactory extends JComponent{
       public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;   
            Color color = new Color(222,222,222);
            Rectangle rect1 = new Rectangle(150, 95, 150, 150, color);
            g2d.setColor(rect1.getColor());
            rect1.drawShape(g2d);
           } 
}

标签: javaswinggraphicsjframe

解决方案


推荐阅读