-2

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
zer0
  • 1
  • 3
  • 2
    Proper painting technique is to use a `JPanel` within the `JFrame` and override `paintComponent()`. Nor should you extend `JFrame` – WJS May 27 '20 at 22:26

2 Answers2

4

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.

Community
  • 1
  • 1
  • Okey. I want to ask one more question. When I add a JPanel to JFrame 3-4 pixel of JPanel overflow from JFrame because that borders. For example my frame's width is 480 but 3-4 pixcel is actually borders. So my content area is actually 474(or something like that) pixel. But my panel is 480 pixel. So some panel's pixel on the out. How I can fix that? – zer0 May 27 '20 at 22:50
0

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().

Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25