Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch to specific JPanel using Cardlayout

I've started working on a Java desktop application using netbeans. I have 7 different screens and to represent them I am using JPanel. One JPanel to represent each of them and one to contain all of them(named as mainPanel), which is inside a JFrame. mainPanel uses Cardlayout for the purpose of switching between screens(JPanels). I built all this interface using netbeans ui widgets i.e. drag drop.

LayOut

JFrame
    mainPanel (Jpanel) CardLayout
        Child1 (JPanel)
        Child2 (JPanel)
        .
        .
        .
        .
        Childn (Jpanel)

I know that one can switch screens using JPanel.next() and Jpanel.previous. but they can only be used when switching is to be done among consecutive screens i.e. if you have to switch to an immediate neighbour. There's also a method JPanel.show() to go to a specific screen but problem is that it takes a parameter name which is a String you associate when you add it to mainPanel using JPanel.add() function. I've added everything using drag and drop, so I don't know what String gets associated, if it does. Although it looks very primitive and I've already done it without Cardlayout but this time, Cardlayout is a requirement.

Help will be highly appreciated

like image 735
moCap Avatar asked Dec 09 '22 21:12

moCap


2 Answers

This example uses a JComboBox to change cards. The example extends JPanel to add a name, but Component has getName() and setName() methods as an alternative. See also this related answer.

image

like image 145
trashgod Avatar answered Dec 11 '22 11:12

trashgod


Well... I got the answer. The thing is, when you add something through interface, code for it is autogenerated which is hidden by default. So, I had to look into the autogenerated code for associated string. by default it is card1, card2, card3 and so on.

The example in answer by trashgod is exactly what I want but not the way i want. It has manually associuated the string in custom Jpanel. But it made me think of looking into the autogenerated code. So, thank You very much :)

Now what I need to do is like

 mainPanel.show (gameHome, "Card3");
like image 36
moCap Avatar answered Dec 11 '22 09:12

moCap