0

I have a class, SheetGood, which extends Rectangle. At the moment I place these SheetGoods onscreen using absolute positions based off of the users resolution, but I'd like to let a layoutmanager take over this aspect.

To do so I'd like to add a SheetGood object to a JPanel, but can't as SheetGood does not extend JComponent.

Any ideas as to how I can get around this?

//edit// Will I run into issues if I force my program to run at a certain size and remove resizing options? Ie, a fixed size of 1280x1024 so I can continue placing SheetGoods how I have been and not have to worry about the other controls clipping them when their layout manager moves them around.

1 Answers1

0

To use absolute positioning, dont use a layout manager. You should set layout to null.

I suggest that: extends JPanel as rectangle and set a background color, and set bounds to the positions you want to place.

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);
}
yavuzkavus
  • 1,268
  • 11
  • 17