Position problem with adding something to JFrame in Java

58 Views Asked by At

I want to add JLabels to JFrame directly. I don't want use JPanel. But I have a position problem. I set layout as null.

I tryed draw line to see what's going on.

@Override
public void paint(Graphics g){
    g.setColor(Color.red);
    g.drawLine(0, 31, super.getWidth(), 31);
}

And the zero is actually 31.

Drawing screenshot
Drawing screenshot

Why? And how can I fix that?

2

There are 2 best solutions below

1
DontKnowMuchBut Getting Better On

I want to add JLabels to JFrame directly. I don't want use JPanel.

If you're adding the JLabel "to the JFrame" then you're adding it to the contentPane which is almost always a JPanel, so 99% of the time, you're still using a JPanel, even without trying to.

But I have a position problem. I set layout as null.

Which is almost always a bad thing to do. This makes for GUI's that don't work on all platforms, fighting against the Java philosophy and structure.

And the zero is actually 31.

Why? And how can I fix that?

Because of the top part of the JFrame is taken up by the OS window's menu bar. The contentPane, starts 31 pixels below the top of the JFrame (in your case -- different for different OS's and screen resolutions).

Best to avoid drawing directly on the JFrame, which is actually composed of many sub-components -- the content pane, the root pane, the glass pane,... and instead draw within the paintComponent method of a JPanel that you either add to the contentPane or make as the contentPane. Then 0,0 is the top left of the usable portion of your main window.

Also, please elaborate more on the underlying reason why you're trying to avoid use of a JPanel. Your issue may in fact be an XY Problem type issue.

2
Charlie Armstrong On

Positions in a JFrame are relative to the edge of the window, not the content pane. To get the dimensions of the content pane, use getContentPane().getWidth() and getContentPane().getHeight().