OK按钮和字符串没有显示在JPanel上



我正在尝试制作一个显示打印语句的面板"你好,世界"以及OK按钮。两人都不会出现在小组中,我不知道为什么。我从一个代码块开始,它应该只创建一个空白的弹出窗口。空白弹出效果很好。我无法添加字符串或按钮并查看它们。我已尝试调用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);移到。

最新更新