确定按钮和字符串未显示在 JPanel 上

OK button and String not showing up on JPanel

我正在尝试制作一个显示打印语句“Hello World!”的面板和一个确定按钮。两者都不会出现在面板上,我不知道为什么。我从一个应该只创建一个空白弹出窗口的代码块开始。空白弹出窗口效果很好。我无法添加字符串或按钮并查看它们。我试过调用 paintComponent。我尝试将内容添加到面板。有谁知道我错过了什么?

这是我的代码


package painting;

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

public class SwingPaintDemo1 {
        
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
        
        private static class SwingPaintDemo extends JPanel{
            public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawString("Hello World!", 20,30);
        }
        }
        
        private static void createAndShowGUI() {
            System.out.println("Created GUI on EDT? "+
                    SwingUtilities.isEventDispatchThread());
            JFrame f = new JFrame("Swing Paint Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(250,250);
            f.setVisible(true);
            
            JButton okbutton = new JButton("OK");
            ButtonHandler listener = new ButtonHandler();
            okbutton.addActionListener(listener);
            
            SwingPaintDemo displayPanel = new SwingPaintDemo();
            JPanel content = new JPanel();
            content.setLayout(new BorderLayout());
            content.add(displayPanel, BorderLayout.CENTER);
            content.add(okbutton, BorderLayout.SOUTH);
        }
        
        private static class ButtonHandler implements ActionListener{
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        }
    }

您忘记将 JPanel 添加到 JFrame。只需在 createAndShowGUI() 方法的底部添加以下行:

f.add(content);

为了安全起见,我还建议将 f.setVisible(true); 行移到方法的底部。当您使框架可见时,组件树将被设置为考虑添加到 JFrame 的所有组件。如果之后添加更多组件,您将需要手动重新验证树或执行一些触发自动重新验证的操作。我假设您不会在任何地方重新验证您的树,所以您应该将 f.setVisible(true); 移动到添加所有组件之后。