【问题标题】:Problem with setVisible(boolean)setVisible(boolean) 的问题
【发布时间】:2011-07-23 19:30:53
【问题描述】:

我有一个JFrame,上面有一些组件。我希望当我点击一个特殊按钮时框架消失,例如exit button

我在退出按钮中写了这段代码

this.setvisible(false);

但它只是隐藏了它上面的组件,框架并没有消失。

当我点击exit button时,框架消失了怎么办?

【问题讨论】:

  • 请出示相关代码。我想this 指的是 JButton 而不是 JFrame。
  • 好吧,setvisible 不会退出程序。
  • @experimentX - 您可以在一个应用程序中拥有多个 JFrame,其中一些可以隐藏一段时间。

标签: java swing visibility


【解决方案1】:

下面是一个隐藏框架的按钮示例:

final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JButton hideButton = new JButton("hide frame");
frame.add(hideButton);
hideButton.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {
      frame.setVisible(false);
   }

});

frame.setVisible(true);
frame.pack();

【讨论】:

    【解决方案2】:

    在您的电话this.setVisible(false) 中,this 可能指的是按钮而不是框架。

    您需要在 Frame 而不是 Button 上调用 setVisible()。

    还要确保在框架上调用 dispose() 以清理所有资源。

    此外,您还应该使用

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    

    在创建框架期间,确保在用户单击右上角的“标准”关闭按钮(在 Windows 上)时正确关闭和处理窗口。

    本教程还可以帮助您更好地了解正在发生的事情:

    http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

    【讨论】:

      【解决方案3】:

      在 JFrame 对象上调用它。 例子: // when exit is pressed

      fr.setVisible(false); // fr is a reference to object of type JFrame`

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        相关资源
        最近更新 更多