有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将扩展矩形类添加到jpanel

我有一个类SheetGood,它扩展了矩形。目前,我使用基于用户分辨率的绝对位置将这些板材放置在屏幕上,但我想让布局经理接管这方面的工作

为此,我想向JPanel添加一个SheetGood对象,但不能,因为SheetGood不扩展JComponent

有什么办法可以解决这个问题吗

//编辑// 如果我强制我的程序以一定的大小运行并删除大小调整选项,我会遇到问题吗? 也就是说,固定大小为1280x1024,这样我就可以继续按原样放置板材,而不必担心其他控件在布局管理器移动板材时会将其剪切


共 (1) 个答案

  1. # 1 楼答案

    要使用绝对定位,请不要使用布局管理器。您应该将布局设置为空

    我建议:将JPanel扩展为矩形,设置背景色,并为要放置的位置设置边界

    static class MyRectangle extends JPanel {
        int x, 
            y,
            width,
            height;
        Color bg;
    
        public MyRectangle(int x, int y, int width, int height, Color bg) {
            super();
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.bg = bg;
            setBounds(x, y, width, height);
            setBackground(bg);
        }
    }
    
    public static void main(String[] args) throws Exception {
        JFrame frame = new JFrame("Test rectangle");
    
        MyRectangle rect1 = new MyRectangle(10, 10, 90, 90, Color.red),
                    rect2 = new MyRectangle(110, 110, 90, 90, Color.yellow);
    
        JPanel contentPane = (JPanel)frame.getContentPane();
        contentPane.setLayout(null); //to make things absolute positioning
    
        contentPane.add(rect1);
        contentPane.add(rect2);
    
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }