简体   繁体   中英

How to navigate to previous card with button in card layout?

I have created a Java application in Netbeans, and used CardLayout to make three cards, which appear when I click three buttons.

All that is fine but I want to make a 'back' icon that, when clicked on, brings the previous card, so that if I am in the third card, clicking on the 'back' icon brings the second card, and from the second card to the first and so on.

The problem is that I want the program to know that we are in the second card for example, so clicking the 'back' icon brings the first card.

Also the back icon is on another panel in the same JFrame . I hope someone helps!

The icon on the lower left is the back button and cards are located inside-the white portion.

图片

I suppose somewhere in your project you already have the following code pieces:

For building the panel on the right (the one with the CardLayout ):

JPanel panel1 = ...;
JPanel panel2 = ...;
JPanel panel3 = ...;
JPanel rightPanel = new JPanel();
CardLayout cardLayout = new CardLayout();
rightPanel.setLayout(cardLayout);
rightPanel.add(panel1);
rightPanel.add(panel2);
rightPanel.add(panel3);

and for building the "back" button (the one with the <- icon):

JButton backButton = ...;

Then all you need to add is the following:

backButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        cardLayout.previous(rightPanel);    
    }
});

or equivalently, if you prefer the concise lambda-syntax of Java 8:

backButton.addActionListener(e -> cardLayout.previous(rightPanel));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM