java - JFrame setContentPane 隐藏其他组件

标签 java swing user-interface jframe jlabel

因此,我将进入 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/

相关文章:

java - 通过 id 而不是对象添加与实体的关系

java - 在 Parse 上存储位置对象

java - 可执行 jar 文件未运行

java - 有没有办法使用 Dropbox API 上传到单个用户的 Dropbox?

java - 获取 jDateChooser 日期到 jLabel

java - 用鼠标发送加速器来执行文本选择

JAVA表单检测变化

user-interface - 使用 tivo/tview GoLang 库时获取实际的表单值

java - 如何对java中ExecutorService内部的相似线程求和?

python - 在wxpython中保存组合框的选定值