[英]Java Gui label does not show up in the desired location on screen
我在 Java Swing 中创建了一个小 GUI,但我在 label 的位置上遇到了一个小问题。 我需要在框架的顶部中心显示 label 但在我的代码中,即使我添加了设置边界,它仍然显示在错误的位置。 如何在中心显示 label?
该面板也没有显示在我的屏幕上。 不知道为什么。
我的代码
public class GuiInterface {
public void GUI()
{
// Frame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Fault Localization");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Fonts
Font f2 = new Font(Font.SANS_SERIF, Font.BOLD, 20);
Font f3 = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
//Components
JPanel mPanel=new JPanel();
mPanel.setBackground(Color.lightGray);
mPanel.setLayout(new BorderLayout());
JButton jb1 = new JButton("Here");
// Text Area
JTextArea fTextArea=new JTextArea();
//fTextArea.setBounds(60,150, 400,400);
fTextArea.setMargin(new Insets(3,3,3,3));
fTextArea.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane(fTextArea);
JLabel tittle= new JLabel("Fault");
// tittle.setBounds(30,30, 400,20);
tittle.setFont(f2);
//Adding the components to the panel
mPanel.add(jb1, BorderLayout.SOUTH);
// Frame Settings
frame.add(mPanel);
frame.add(tittle);
frame.pack();
frame.setVisible(true);
frame.setSize(800,800);
}
}
我的代码的更新版本
Label 与面板一起出现,但面板中添加的组件不显示。
public class GuiInterface {
public void GUI()
{
// Frame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Fault");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
//Fonts
Font f2 = new Font(Font.SANS_SERIF, Font.BOLD, 20);
Font f3 = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
JPanel fPanel=new JPanel();
fPanel.setBackground(Color.BLUE);
fPanel.setLayout(new BorderLayout());
JButton jb1 = new JButton("Here");
// Text Area
JTextArea fTextArea=new JTextArea();
//fTextArea.setBounds(60,150, 400,400);
fTextArea.setMargin(new Insets(3,3,3,3));
fTextArea.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane(fTextArea);
JLabel tittle= new JLabel("Fault Localization",JLabel.CENTER);
tittle.setFont(f2);
//Adding the components to the panel
fPanel.add(jb1, BorderLayout.NORTH);
fPanel.add(fTextArea, BorderLayout.SOUTH);
// Frame Settings
frame.add(fPanel,BorderLayout.CENTER);
frame.add(tittle,BorderLayout.NORTH);
frame.setVisible(true);
frame.setSize(800,800);
}
}
我不知道结果应该是什么样子。 但是您没有为 JFrame 分配特定的布局,只需将 Label 添加到 JFrame 即可。
JFrame 的默认布局是 BorderLayout。 如果您希望组件出现在特定的 position(例如顶部的示例),您必须指定区域。 BorderLayout 有 5 个不同的区域:NORTH、EAST、SOUTH、WEST 和 CENTER。
因此,您可能应该做的是 JFrame.add(JLabel, BorderLayout.NORTH) 将 label 分配在 JFrame 的顶部。
顺便说一句,您不应该同时使用 JFrame.pack 和 JFrame.setSize(),并且 JFrame.setVisible() 应该始终是您的最后一个方法调用。 在您的示例中,它没有区别,但如果您决定在方法调用之后添加组件,它会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.