【发布时间】:2018-12-13 22:02:53
【问题描述】:
我正在尝试在 GUI 中制作 RPG 游戏,但进展并不顺利。 在我添加 JButton 之前,一切都正常工作并按应有的方式显示在窗口中。我不确定添加 JButton 后发生了什么。 应该在灰色区域显示标题,在蓝色区域显示按钮。我试过正常运行并使用调试器运行,没有显示任何文本或按钮。 我正在一步一步地按照教程here 进行操作,我没有看到任何不合适的地方。 (我知道我已经更改了变量名)。
我在这里做错了什么?我需要添加什么额外的东西吗?
import javax.swing.*;
import java.awt.*;
public class Game {
JFrame window;
Container c;
JPanel titlePanel;
JPanel startButtonPanel;
JLabel titleLabel;
JButton startButton;
Font titleFont = new Font("Cooper Black", Font.PLAIN, 90);
Font buttonFont = new Font("Cooper Black", Font.PLAIN, 32);
public static void main(String[] args) {
new Game();
}
public Game() {
//Main Window
window = new JFrame();
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null);
window.setVisible(true);
c = window.getContentPane();
//Title Panel
titlePanel = new JPanel();
titlePanel.setBounds(100, 100, 600, 150);
titlePanel.setBackground(Color.GRAY);
titleLabel = new JLabel("TEXT RPG");
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(titleFont);
//Start Button Panel
startButtonPanel = new JPanel();
startButtonPanel.setBounds(300, 400, 200, 100 );
startButtonPanel.setBackground(Color.BLUE);
//Start Button
startButton = new JButton("START");
startButton.setBackground(Color.BLACK);
startButton.setForeground(Color.WHITE);
startButton.setFont(buttonFont);
//Add Elements to Window
titlePanel.add(titleLabel);
startButtonPanel.add(startButton);
//Add Elements to Container
c.add(titlePanel);
c.add(startButtonPanel);
}
}
【问题讨论】:
-
1)
window.setLayout(null);Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2)window.setVisible(true);只有在添加了所有组件并调用了pack()之后才应该这样做。
标签: swing user-interface jframe jbutton jlabel