Iain
Iain

Reputation: 1734

Java Swing resize BorderLayout.CENTER

As the title says, can I redefine the height and width of Java's BorderLayout.CENTER? I plan to use Graphics2D to draw to this area but I won't always know ahead of time how big it should be to fit everything in.

Draw class (declared inside my Main class):

@SuppressWarnings("serial")
private class Draw extends JComponent {
    public void paint(Graphics graphics) {
        Graphics2D g = (Graphics2D) graphics;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        Shape drawLine = new Line2D.Float(0, 0, 500, 500);

        g.setPaint(Color.BLACK);
        g.draw(drawLine);
    }
}

Main constructor where Draw is called:

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 640, 480);
    setJMenuBar(getMenuBar_1());
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));
    contentPane.add(getPanelControls(), BorderLayout.SOUTH);
    contentPane.add(getPanelInfo(), BorderLayout.EAST);
    contentPane.add(new Draw(), BorderLayout.CENTER);
}

I'm currently drawing directly to BorderLayout.CENTER. Should I be drawing to a JPanel and use it's setPreferredSize() method?

Upvotes: 0

Views: 1939

Answers (2)

Masudul
Masudul

Reputation: 21961

Don't assign the fixed pixel at Graphics. Use getHeight() and getWidth() methods to get dynamic size. Use that size to draw your Line.

 int width=getHeight();
 int height=getHeight();

 Shape drawLine = new Line2D.Float(width/2, height/2, width/2+500, height/2+500);

Upvotes: 0

mKorbel
mKorbel

Reputation: 109813

As the title says, can I redefine the height and width of Java's BorderLayout.CENTER? I plan to use Graphics2D to draw to this area but I won't always know ahead of time how big it should be to fit everything in.

(answer only to topic)

  • override its getPreferredSize

  • then any sizing are contraproductive, call JFrame.pack(); before JFrame.setVisible(true);

  • create a JFrame as local variable

EDIT


  • override paintComponent() instead of paint(), 1st code line inside paintComponent() should be super.paintComponent(), otherwise painting cumulated

  • Shape drawLine = new Line2D.Float(0, 0, 500, 500); should be getHeight/Weight() instead of 500, 500

Upvotes: 2

Related Questions