当我将主机布局设置为 null 并运行应用程序时,它不会显示任何内容,但如果我将其设置为 flowlayout (),它会显示标签。我不想使用 flowlayout,因为我想设置边界并指定每个组件的坐标。下面的代码有什么问题?
public class pr8 extends JFrame
{
Font font;
Map attributes;
JPanel MainFrame;
JPanel PicFrame;
JLabel MainTitle;
JLabel Name;
JTextField NameInput;
public pr8 (String Title)
{
super (Title);
MainFrame = new JPanel ();
this.add (MainFrame);
MainFrame.setVisible (true);
MainFrame.setLayout (null);
MainTitle = new JLabel("Student Entry Form");
MainFrame.add (MainTitle);
MainTitle.setFont(new Font("Serif", Font.PLAIN, 24));
font = MainTitle.getFont();
attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
MainTitle.setFont(font.deriveFont(attributes));
MainTitle.setBounds(400, 50, 200, 30);
Name = new JLabel ("Enter your name");
MainFrame.add (Name);
Name.setFont(new Font("Serif", Font.PLAIN, 24));
Name.setBounds (100, MainTitle.getY () + 50, 30, 30 );
NameInput = new JTextField ("Name");
MainFrame.add (NameInput);
NameInput.setBounds(Name.getX() + 30, Name.getY(), 60, 30);
}
}
最佳答案
如果您将 JPanel 的布局设置为 null,则可能需要设置 JPanel 的大小:
panel.setPreferredSize(new Dimension(400, 300));
//In your case: mainFrame.setPreferredSize( /*your dimension*/ );
还要确保您在 JFrame 上调用 pack()
并且 JFrame 的布局不为 null。
关于java - 当我将布局设置为空时,为什么无法使框架可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243851/