[英]Change content pane of JFrame and new component not displaying
I'm making a game and I'm trying to switch between different JPanel
s to display the menu, world etc. 我正在做一个游戏,试图在不同的
JPanel
之间切换以显示菜单,世界等。
public static void setComponent(Component component){
frame.getContentPane().removeAll();
frame.getContentPane().add(component, 0);
}
This is the method to change the component of the JFrame
frame, this works for the first time with whichever JPanel
component I give it, but when I try to change it from inside any class from a keyListener method say, the content pane doesn't display anything. 这是一种更改
JFrame
框架的组件的方法,该方法首次使用我提供的任何JPanel
组件,但是当我尝试从keyListener方法的任何类内部进行更改时,内容窗格都不会显示任何东西。
@Override
public void mousePressed(MouseEvent arg0) {
Frame.setComponent(new MenuPanel());
}
Method to create the JFrame
and the thread that repaints the components 创建
JFrame
方法和重新绘制组件的线程
public static void createFrame(){
frame = new JFrame();
frame.setSize(size);
frame.setTitle(title);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(1,1,0,0));
new Thread(){
public void run(){
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(frame.getComponentCount() != 0){
//System.out.println("?");
frame.getContentPane().repaint();
System.out.println(frame.getContentPane().getComponentAt(1, 1));
}
}
}
}.start();
setComponent(new MenuPanel());
frame.setVisible(true);
}
Getting this result from the Output Stream when first loading 首次加载时从输出流获取此结果
Menu.MenuPanel[,0,0,794x571,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Then after using the setComponent
method from another class 然后在使用另一个类的
setComponent
方法之后
javax.swing.JPanel[null.contentPane,0,0,794x571,invalid,layout=java.awt.GridLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
When you call your setComponent
method the first time, you do that before you call frame.setVisible(true)
that forces the frame to validate all its components and show them. 第一次调用
setComponent
方法时,需要先执行此操作,然后再调用frame.setVisible(true)
,以强制框架验证其所有组件并显示它们。 When you change the components later you need to revalidate your frame manually so it gets aware of its components. 以后更改组件时,您需要手动重新验证框架,以使其了解其组件。 Add these lines to your
setComponent
method and it should work. 将这些行添加到
setComponent
方法中,它应该可以工作。
public static void setComponent(Component component){
frame.getContentPane().removeAll();
frame.getContentPane().add(component, 0);
frame.revalidate(); // revalidate all the frame components
frame.repaint(); // and repaint the frame
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.