[英]Card Layout showing wrong panel
One panel is added through method where card layout is. 通过卡布局的方法添加一个面板。 And another is passed to a method through the object.
另一个通过对象传递给方法。 The problem is that the Panel of a card Layout is showing panel "1" instead of panel "2",like panel "2" is not even passing to a method.
问题是卡片布局的面板显示的是面板“ 1”而不是面板“ 2”,就像面板“ 2”甚至没有传递给方法一样。 There are no errors....
没有错误。
I tried to simplify code as much as i could: 我试图尽可能简化代码:
First class: 头等舱:
public class Game extends JFrame {
private CardLayout cl;
private JPanel MAIN;
private JPanel FIRST;
public Game(){
FIRST = new JPanel();
FIRST.setLayout(new BorderLayout());
cl = new CardLayout();
MAIN = new JPanel();
MAIN.setLayout(cl);
}
public void Show(){
MAIN.add(FIRST, "1");
cl.show(MAIN, "2");
add(MAIN);
}
public void addPanel2(JPanel panel){
MAIN.add(panel, "2");
}
}
Second class: 第二类:
public class meni {
private JPanel SECOND;
Game nova = new Game();
public meni(){
SECOND = new JPanel();
SECOND.setLayout(new GridBagLayout());
nova.addPanel2(SECOND);
}
}
Main class: 主班:
public static void main(String[] args){
Game ticFrame = new Game();
meni luk = new meni();
ticFrame.show();
ticFrame.setTitle("Hey");
ticFrame.setSize(600,600);
ticFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ticFrame.setLocationRelativeTo(null);
ticFrame.setVisible(true);
}
}
You're adding your second JPanel just fine, but you're adding it to the wrong Game object. 您刚刚添加了第二个JPanel,但是您将其添加到了错误的 Game对象。 A Game object is currently visible on program start up, and within that second class you create a completely new and unique Game object and add your second JPanel to that, so it makes sense that it won't show in the visualized object.
当前在程序启动时可以看到一个Game对象,在第二个类中,您将创建一个全新的唯一Game对象,并向其中添加第二个JPanel,因此它不会显示在可视化对象中是有意义的。
Solution: Don't create a new Game object in the second class, but instead make sure that the second class has a valid reference to the visualized Game object. 解决方案:不要在第二个类中创建新的Game对象,而应确保第二个类对可视化 Game对象具有有效的引用。 This can be done through a constructor parameter or a setter method parameter.
这可以通过构造函数参数或setter方法参数来完成。
nova.addPanel2(SECOND); nova.addPanel2(SECOND); what do you mean from this code??
您从这段代码中指什么? to add panel to frame we have methos such as JPanel.add( your panel object).
为了将面板添加到框架中,我们有一些方法,例如JPanel.add(您的面板对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.