因此,我将进入 Java 中的 GUI,并尝试为计时器创建一个简单的主菜单。一切都很好,直到我尝试为 GUI 添加背景。添加背景有效,但是所有其他组件现在都消失了(按钮)。我该如何解决这个问题?
编辑:这是我的新代码。
公共(public)类 MainMenu {
// JFrame = the actual menu / frame.
private JFrame frame;
// JLabel = provides text instructions or information on a GUI —
// display a single line of read-only text, an image or both text and an image.
private JLabel background;
// JButton = button.
private JButton alarmClockButton;
// Constructor to create menu
public MainMenu() {
frame = new JFrame("Alarm Clock");
alarmClockButton = new JButton("Timer");
// Add an event to clicking the button.
alarmClockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: CHANGE TO SOMETHING NICER
JOptionPane.showMessageDialog(null, "This feature hasn't been implemented yet.", "We're sorry!",
JOptionPane.ERROR_MESSAGE);
}
});
// Creating the background
try {
background = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResourceAsStream("/me/devy/alarm/clock/resources/Background.jpg"))));
} catch (IOException e) {
e.printStackTrace();
}
frame.setLayout(new FlowLayout());
frame.setContentPane(background);
frame.add(alarmClockButton);
frame.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame.setVisible(true);
frame.setSize(450, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
alarmClockButton.setForeground(Color.RED);
}
谢谢!
最佳答案
frame.setContentPane(background);
您将标签用作内容 Pane 。问题是标签默认不使用布局管理器。
你需要添加:
background.setLayout( new BorderLayout() ); // or whatever layout you want
frame.setContentPane(background);
现在您可以将按钮直接添加到框架中。你不需要面板。
或者如果你想变得更有趣,你可以使用 Background Panel这使您可以选择缩放或平铺背景图像。
关于java - JFrame setContentPane 隐藏其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901768/