簡體   English   中英

將擴展的矩形類添加到jpanel

[英]Add extended rectangle class to jpanel

我有一個類SheetGood,它擴展了Rectangle。 目前,我根據用戶分辨率使用絕對位置將這些Shee​​tGoods放置在屏幕上,但是我想讓布局管理器來接管這方面的工作。

為此,我想將一個SheetGood對象添加到JPanel中,但是不能這樣做,因為SheetGood不會擴展JComponent。

關於如何解決這個問題有什么想法嗎?

// edit //如果我強制程序以特定大小運行並刪除調整大小選項,是否會遇到問題? 即,固定尺寸為1280x1024,因此我可以繼續按原樣放置SheetGoods,而不必擔心其他控件在布局管理器中移動時會修剪它們。

要使用絕對定位,請不要使用布局管理器。 您應該將layout設置為null。

我建議:將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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM