ClassCastException on CardLayout

huangapple go评论116阅读模式
英文:

ClassCastException on Cardlayout

问题

I'm on that stage of learning Java where you get to make GUIs. For this program, I'm using CardLayout for swapping between panels. The problem is, I get this error over and over. I've searched everywhere and I still cannot solve it. The error as shown on console is:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class java.awt.FlowLayout cannot be cast to class java.awt.CardLayout (java.awt.FlowLayout and java.awt.CardLayout are in module java.desktop of loader 'bootstrap')

The console said my problem is on this part of the code:

public FrameMenuPrincipal() {
    initComponents();
    deffbg = new JPanel();
    deffbg.add(pane1, "panewelc");
    deffbg.add(pane2, idcreate);
    deffbg.add(pane3, idsite);
    
    cl = (CardLayout)(deffbg.getLayout());
    cl.show(deffbg, idmenu);
}

deffbg being the parent panel;

For adding more context, I've been using this tutorial, and I'm programming in NetBeans, using the GUI builder.

英文:

I'm on that stage of learning Java where you get to make GUIs. For this program, I'm using CardLayout for swapping between panels. The problem is, I get this error over and over. I've searched everywhere and I still cannot solve it. The error as shown on console is:

> Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class java.awt.FlowLayout cannot be cast to class java.awt.CardLayout (java.awt.FlowLayout and java.awt.CardLayout are in module java.desktop of loader 'bootstrap')

The console said my problem is on this part of the code:

public FrameMenuPrincipal() {
    initComponents();
    deffbg = new JPanel();
    deffbg.add(pane1, "panewelc");
    deffbg.add(pane2, idcreate);
    deffbg.add(pane3, idsite);
    
    cl = (CardLayout)(deffbg.getLayout());
    cl.show(deffbg, idmenu);
}

deffbg being the parent panel;

For adding more context, I've been using this tutorial, and I'm programming in NetBeans, using the GUI builder.

答案1

得分: 1

默认情况下,JPanel 使用了 FlowLayout。如果你想使用其他布局管理器,你可以在构造函数中提供它。所以在这种情况下,如果你想使用 CardLayout,你可以像这样实例化它:

deffbg = new JPanel(new CardLayout());
英文:

By default, JPanel used a FlowLayout. If you want to use something different, you can provide it in the constructor. So in this case, if you wanted to use a CardLayout you could instantiate it like this:

deffbg = new JPanel(new CardLayout());

huangapple
  • 本文由 发表于 2023年4月7日 03:28:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定