import java.awt.*;
import javax.swing.*;
public class JFrameGUI extends JFrame
{
JLabel item1;
public JFrameGUI(int l, int b , String Title)
{
setTitle(Title);
setLayout(new FlowLayout());
setSize(l, b);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
item1 = new JLabel("This is a Sentence.");
item1.setToolTipText("This is gonna show up on hover.");
add(item1);
}
public static void main(String[] args)
{
JFrameGUI g = new JFrameGUI(1280,720,"The End Of The Line");
JPanel p = new JPanel();
p.setBackground(Color.BLUE);
g.add(p);
}
}
When I execute this , all i get is a tiny Blue square nest to the "This is a sentence" string . I've tried everything !
You need to set the layout of the frame to a layout that doesn't
respect the preferred sizes of its children. FlowLayout
does, and your JPanel
has no preferred size without any components added to it, or specifying a preferred size.
A simple fix, set the layout of the frame to BorderLayout
, or not set a layout at all, since JFrame
already has a default BorderLayout
. Note though that you probably want to add the JLabel
to the JPanel
and not the JFrame
. Unless you do want to add it the JFrame
and not the background JPanel
, you need to specify a BorderLayout
position for the one you don't want in the center.
You can see this answer to see which layout managers respect preferred sizes and which don't
See more at Layout out Components Withing a Container
Also, setVisible(true)
shoul be the last thing you do after adding all components.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.