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

public class Class4 {

    public static final long serialVersionUID = 1L;

    public void mainMethod(int event){
        JFrame f = new JFrame("Love Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,200);     
        f.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();

        if(event == 0){




            JPanel p = new JPanel();
            p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
            p.setBounds(150, 0, 500, 75);
            p.setPreferredSize(new Dimension(150,75));
            JTextField boy = new JTextField();
            boy.setMaximumSize(new Dimension(200,40));
            JTextField girl = new JTextField();
            girl.setMaximumSize(new Dimension(200,40));
            p.add(boy);
            p.add(girl);
            gbc.insets = new Insets(-90,310,0,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p,gbc);

            JPanel p3 = new JPanel(new BorderLayout());
            p3.setBounds(0, 0, 150, 75);
            p3.setPreferredSize(new Dimension(150,75));
            Class5 c5o = new Class5();
            c5o.setPreferredSize(new Dimension(150,75));
            p3.add(c5o);
            gbc.insets = new Insets(0,0,90,330);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p3,gbc);

            JPanel p2 = new JPanel(new FlowLayout());
            Class7 c7o = new Class7();
            p2.add(c7o);
            p2.setPreferredSize(new Dimension(300,40));
            gbc.insets = new Insets(0,0,-20,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p2,gbc);

            f.setVisible(true);

            //1st
            JOptionPane.showMessageDialog(null,f.isDisplayable());


        }

        if(event == 5){

            JPanel p4 = new JPanel(new BorderLayout());
            p4.setBounds(0,140,500,55);
            Class2 c2o = new Class2();
            Dimension d2 = new Dimension(500,55);
            c2o.setPreferredSize(d2);
            p4.setPreferredSize(d2);
            p4.add(c2o);
            gbc.insets = new Insets(0,0,-130,0);
            gbc.gridx = 0;
            gbc.gridy = 0;

            f.add(p4,gbc);

            f.invalidate();
            f.validate();
            f.repaint();

            //2nd
            JOptionPane.showMessageDialog(null,f.isDisplayable());
        }

    }

}

我第一次测试时f.isDisplayable(),它返回了 true。但是,第二次,在重新验证并重新绘制 JFrame 之后,它返回 false。结果我无法在 JFrame 上显示我的 JPanel。如何将我的 JPanel 添加到 JFrame 并使其显示出来?为什么f.isDisplayable()第二次返回false?if语句有问题吗?

4

0 回答 0