Friday, November 13, 2009

CardLayout With Netbeans

Here is a simple tutorial that illustrates the use of CardLayout with the Netbeans GUI-Builder. For this I am using Netbeans 6.7.1.

1. Create a Java Desktop Application.

2. Name your application CardTester (or whatever you want, I am going to name mine CardTester). Make sure you choose an appropriate name for your Application Class including the package name.

Click Finish when you are done. The application is created.

3. Ensure that the Inspector window is visible. If not look in the Window > Navigation menu for it.
In the Inspector Window you can see all the components that make up your user interface and how they are associated with each other. The default application is made up of the main application window along with a mainPanel and a menu bar and a statusPanel. We will add a CardLayout to the mainPanel.

4. Right click on the mainPanel, select Set Layout from the context menu then select Card Layout.

5. Now lets us drag two cards onto the mainPanel. From the Palette window, click on Panel and drag it onto the mainPanel. You will see the panel under the mainPanel in the Inspector window. Make sure that the new panel is selected and change some properties.

name : card1
Card Name: card1

Change any other property that you wish.

6. Repeat step 5 to add another card. Lets call this one card2. The Inspector window should now look like to following illustration.

7. Lets add some content to the cards so that we will be able to see them change. Make sure that card1 is selcted and drag a label onto the card, set any text you wish. Next select card 2 and do the same.

8. Now we can add some functionality that will cause the cards to flip. For this we can use a single button that will flip the cards as it is clicked. Drag a button to the status panel. Right click on the button and choose Set Action... from the menu.

From the Action drop down select New Action... type in a Method Name for the action. You may also add the display text, tooltip and accelerator for the Button.

Click OK when ready. The code view becomes visible. The method that you choose is added to the code.

9. Add code.

public void cardSwitcher() {
CardLayout cl = (CardLayout)(mainPanel.getLayout());;

10. Run the application. If you are really really lucky, when you click the button the cards will change.

I hope this very simple tutorial makes it a bit easier to use the Netbeans GUI-Builder to create a Card Layout.

For more info on using the Card Layout itself visit this page.
Post a Comment