In the code below, the JFrame
contains JLabel
only, in the center of BorderLayout
.
package test.swing;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Try_JLabel_01 {
public static void main(String[] arg) {
JFrame frame = new JFrame() {
JLabel label = new JLabel("label");
{
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}
};
frame.pack();
//frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
If ran, this program shows window, which fits exactly the control size.
Simultaneously, if I define my custom control, then default window is of zero size:
public class Try_JLabel_02 {
public static void main(String[] arg) {
JFrame frame = new JFrame() {
//JLabel label = new JLabel("label");
JComponent label = new JComponent() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(0, 0, 200, 100);
}
};
{
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}
};
frame.pack();
//frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
How to extend JComponent correctly, so that it behaves like JLabel and, for example, has the default size of 200x100?
P.S. I don't want to extend JLabel
. I want to learn how JLabel
does extending JConmponent
instead.
I see source code of JLabel
, but I can't understand, how do they control the sizes. Actually I see no any size control code at all there.
UPDATE
I found that can solve the task if I not override, but if I set the sizes:
//JLabel label = new JLabel("label");
JComponent label = new JComponent() {
{
setMinimumSize(new Dimension(200, 100));
setPreferredSize(new Dimension(200, 100));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(0, 0, 200, 100);
}
};
But this works only in case I know sizes myself. In the case of font, I can't know size without having Graphics
object first.
So how to determine sizes in case of a font?