简体   繁体   English

如何使用卡片布局中的按钮导航到上一张卡片?

[英]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. 我在Netbeans中创建了一个Java应用程序,并使用CardLayout制作了三张卡,当我单击三个按钮时,它们会出现。

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 . 后退图标也位于同一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 ): 为了在右侧构建面板(使用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: 或等效地,如果您喜欢Java 8的简洁lambda语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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