如何从另一个类调用JPanel

时间:2019-01-09 17:05:10

标签: methods jframe jpanel

我在一个类中添加了带有JButton的JPanel。我在另一个类中有一个JFrame,还有一个方法可以让您从第二个类中获取JPanel。当我将JFrame的contentpane设置为JPanel时,它是黑色的,但是,如果我将JFrame放在JPanel类中,则它可以正常工作。谢谢您的帮助。

第一类:

public class one {
private static JPanel p = new JPanel();

public one() {

    p.setVisible(true);
    p.setBackground(Color.BLACK);
    p.setLayout(new GridLayout(3, 3, 25, 25));

    JButton b = new JButton("Testing");
    b.setBounds(60, 60, 100, 100);
    b.setVisible(true);



    p.add(b);


}
public static JPanel getP() {
    return p;
}
}

第二课:

public class two {

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(null);
    f.setBounds(10, 10, 500, 500);
    f.setContentPane(one.getP());



    f.setVisible(true);
}

}

1 个答案:

答案 0 :(得分:0)

尝试从一个类中删除static关键字,因为您正在一个人的构造函数中执行jpanel操作。请记住,从该类创建新对象时会调用构造函数。将jpanel设为静态并调用jpanel wihtout创建新的一个实例时,将不会执行jpanel操作。所以您的路线可以在下面:

public one() {

    p.setVisible(true);
    p.setBackground(Color.BLACK);
    p.setLayout(new GridLayout(3, 3, 25, 25));

    JButton b = new JButton("Testing");
    b.setBounds(60, 60, 100, 100);
    b.setVisible(true);



    p.add(b);


}
public JPanel getP() {
    return p;
}
}

public static void main(String[] args) {
    JFrame f = new JFrame();
    one o = new one();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(null);
    f.setBounds(10, 10, 500, 500);
    f.setContentPane(o.getP());



    f.setVisible(true);
}

}
相关问题