【问题标题】:JButton positioning, does not appearJButton定位,不出现
【发布时间】:2016-04-10 00:18:36
【问题描述】:

在我的代码中,我有一个打开主菜单的 JFrame,在该菜单中您可以单击选项,这将带您进入选项菜单。在那个选项菜单上,我想创建一个后退按钮,它将自己定位在屏幕左上角的某个位置。当我运行程序并转到选项菜单时,JButton 不会出现。我的代码一定有问题。有什么帮助吗?下面是我第一次声明 JButton 的地方。

    static JButton optionsBackButton = new JButton("<html><font size = 5 
           color = green>Back</font></html>"); 

这是与 JButton 相关的另一部分代码。

    //Options Menu
    JPanel optionsPanel = new JPanel();
    JLabel optionsOptionsTitle = new JLabel("<html><font size = 7 color = blue>Options</font></html>");
    JPanel optionsOptionsTitlePanel = new JPanel();
    JPanel optionsBackButtonPanel = new JPanel();

    optionsPanel.setLayout(null);
    optionsBackButton.setBounds(100,100,50,50);

    optionsBackButtonPanel.add(optionsBackButton);
    optionsOptionsTitlePanel.add(optionsOptionsTitle);
    optionsPanel.add(optionsOptionsTitlePanel);
    optionsPanel.add(optionsBackButtonPanel);

    optionsBackButton.addActionListener(this);

    //Add panels to the card
    panel.add("Home Screen", homePanel);
    panel.add("Options Menu", optionsPanel);
    //card.add("Game screen", gamePanel);
    cardLayout.show(panel, "HomeScreen");
    contentPane.add(panel);

【问题讨论】:

  • 您有很多需要纠正的地方,包括过度使用静态字段、在可能应该使用 JDialog 的地方使用 JFrame,以及最重要的是使用 null 布局和 setBounds(...)应该使用有效的布局管理器。不过,要获得更全面的帮助,请发布您最好的 minimal reproducible example,让我们帮助您改进这一点。

标签: java swing jbutton layout-manager cardlayout


【解决方案1】:

您的问题源于您使用null 布局。注意:

JPanel optionsBackButtonPanel = new JPanel(); // holds the back button
                                              // but never given a size

optionsPanel.setLayout(null);    // uh oh,.... bad news
optionsBackButton.setBounds(100,100,50,50);   // yes you set the bounds of the button

optionsBackButtonPanel.add(optionsBackButton);
optionsOptionsTitlePanel.add(optionsOptionsTitle);
optionsPanel.add(optionsOptionsTitlePanel);
optionsPanel.add(optionsBackButtonPanel);  // again, optionsBackButtonPanel 
                              // has been never given a size or location/bounds

optionsBackButton.addActionListener(this);

因此,您设置按钮的边界并将其添加到使用默认 FlowLayout 的 JPanel,因此边界没有意义。然后,将该 JPanel(您从未设置其边界)添加到使用空布局的 JPanel。所以 optionsBackButtonPanel 永远不会显示。

解决方案:不要使用空布局,而是学习和使用布局管理器。

虽然空布局和setBounds() 在 Swing 新手看来是创建复杂 GUI 的最简单和最好的方法,但创建的 Swing GUI 越多,使用它们时遇到的困难就越严重。当 GUI 调整大小时,它们不会调整您的组件大小,它们是增强或维护的皇家女巫,放置在滚动窗格中时它们完全失败,在与原始不同的所有平台或屏幕分辨率上查看时它们看起来很糟糕.

从这里开始:Laying Out Components in a Container Tutorial

【讨论】:

    猜你喜欢
    • 2013-10-17
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多