我正在尝试创建一个GUI,我想在某些地方放置元素。我使我的面板布局为null,所以我可以做到这一点。但是,当面板为空时,不会显示任何内容。
这是代码:
public class OverView extends JFrame {
//height and width of screen
Toolkit tk = Toolkit.getDefaultToolkit();
int x = ((int) tk.getScreenSize().getWidth());//length of screen
int y = ((int) tk.getScreenSize().getHeight());//height
//components
private JLabel title;
private JLabel description;
private JPanel panel;
private ArrayList<JButton> farms;
//farm variables
public ArrayList<Farm> owned;
public OverView(ArrayList<Farm> owned) {
super("The Lolipop Farm - Overview");
setSize(700, 700);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
//initialize variables
this.owned = owned;
panel = new JPanel();
panel.setLayout(null);
title = new JLabel("<html>Your Farms - The Lolipop Farm"
+ "<br> <font size=1000> <i> An Eph Production </i> </font></html>");
//set background color, color, and font of JComponents
title.setFont(new Font("serif", Font.BOLD, 25));
title.setBackground(Color.GRAY);
title.setOpaque(true);
//set size and location of the components
title.setSize(350, 120);
title.setLocation(x / 2, 600);
//add to panel
panel.add(title);
//add panel to the screen
add(panel);
}
}
当布局为空时,为什么面板不显示任何内容?
答案 0 :(得分:2)
由于概述是一个框架,我认为你必须调用方法
setVisible(true);
根据https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html以使其可见。 现在,如果这不起作用,我想知道您是否在代码中的其他位置或Main方法中创建了Overview类的实例。如果还没有,那么没有任何对象可以显示您班级内的面板,因此您的程序不会显示任何内容。
答案 1 :(得分:0)
您的问题在于代码
setLayout(null);
这会将JFrame的布局设置为null,因为您正在扩展(继承它)。您必须具有JFrame的布局,尽管您可以不使用JPanel的布局。只需删除该行即可。
修改: 当然,你需要像其他人一样调用setVisible(true)。