[英]Components not showing up in Java Swing
我是 Java 和 Java GUI 的新手,我在使用 Java Swing 时遇到了问题。 目前我有以下代码:
public class Dashboard {
Dashboard() {
JFrame screen = new JFrame();
JPanel window = new JPanel();
JLabel title = new JLabel();
title.setText("dashboard");
title.setBounds(400,200,100,100);
title.setVisible(true);
window.add(title);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
File xkcd = new File("./bin/gui/xkcd-script.ttf");
Font xkcdscript;
try {
xkcdscript = Font.createFont(0, xkcd);
ge.registerFont(xkcdscript);
title.setFont(xkcdscript);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JMenuBar sidebar = new JMenuBar();
window.setLayout(new FlowLayout());
window.add(sidebar);
window.add(title);
screen.add(window);
screen.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
screen.setVisible(true);
}
在我添加 JPanel 之前,我显示了侧边栏,但是在添加它之后,我的所有元素都消失了。 到目前为止,我尝试过的一切都没有帮助。 我正在使用 Eclipse 和 Java13。
我应该改变什么?
欢迎詹姆斯。 作为一个新的贡献者,如果有帮助,请确保接受这个答案。
您构建代码的方式会让您非常头疼。 首先,您应该从 Dashboard 类扩展 JFrame,然后使用 main 方法来实例化您的框架,然后使用构造函数 public Dashboard(),您可以在其中添加所有组件。
像这样的东西:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Dashboard extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Dashboard frame = new Dashboard();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Dashboard() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
希望这会有所帮助并祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.