Java setVisible(false) 不会使 swing Jframe 不可见

Java swing Jframe won't be invisible by setVisible(false)

我今天才开始使用 java swing 编码,所以我是新手,如果我的问题很愚蠢,我深表歉意。我在网上搜索了很多,但什么也没找到。

我的问题是我无法通过 setVisible(false) 使 Jfraim 不可见。

代码非常简单。 window 只有一个按钮,点击后会显示 showMessageDialog "Hello World",我希望 window 在那之后不可见。

这是我的代码:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Temp extends JFrame{
    private JPanel panel1;
    private JButton button1;

    private Temp() {
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                JOptionPane.showMessageDialog(null, "Hello World");
            }
        });
    }


    public static void main(String[] args) {
        JFrame tempWindow = new JFrame("TempWindow");
        tempWindow.setContentPane(new Temp().panel1);
        tempWindow.setLocationRelativeTo(null); // this line set the window in the center of the screen
        tempWindow.setDefaultCloseOperation(tempWindow.EXIT_ON_CLOSE);
        tempWindow.pack();
        tempWindow.setVisible(true);

    }

}

我不知道我做错了什么。我所做的一切都像 this youtube video 但我的 window 在单击按钮后不会变得不可见。

如有任何帮助,我们将不胜感激。

试试这个。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Temp {
   private JPanel  panel1;
   private JButton button1;

   JFrame          tempWindow = new JFrame("TempWindow");

   private Temp() {
      button1 = new JButton("Button");
      tempWindow.add(button1);
      button1.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            tempWindow.setVisible(false);
            JOptionPane.showMessageDialog(null, "Hello World");
         }
      });
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(() -> new Temp().start());

   }

   public void start() {
      tempWindow.setLocationRelativeTo(null); // this line set the window in the
                                              // center of the screen
      tempWindow.setPreferredSize(new Dimension(500, 500));
      tempWindow.setDefaultCloseOperation(tempWindow.EXIT_ON_CLOSE);
      tempWindow.pack();
      tempWindow.setLocationRelativeTo(null); // centers on screen
      tempWindow.setVisible(true);

   }

}
  • 我删除了面板,因为没有必要演示 解决方案
  • 我还创建了一个按钮,因为你没有
  • 扩展 JFrame 也被认为是不好的做法。最好是 扩展 JPanel 并在 JFrame 实例中放置一个实例。但是,如果您不打算重写某些内容,最好使用组合而不是继承。