gpt4 book ai didi

java - CardLayout 不显示下一张卡

转载 作者:行者123 更新时间:2023-11-30 06:57:58 25 4
gpt4 key购买 nike

我在显示下一张卡片的卡片布局时遇到了麻烦,我在这里阅读了文档和各种线程。代码“有效”,但如上所述,不显示下一张卡片。三张卡分别工作,但通过next()方法访问时不可见

这是代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Start {

public static void main(String[] args) {
new Start().createFrame();
}

public void createFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Card().createMainGui();
}
});
}

class Card1 extends Card {

public Card1() {
createGui();
}

private void createGui() {
/*
* Create buttons and add them to the Card1 Panel
*/

final JButton button = new JButton("Next");
button.addActionListener(this);

add(button);
}
}

class Card2 extends Card {

public Card2() {
createGui();
}

private void createGui() {
/*
* Create label and add it to the Card2 Panel
*/

JLabel label = new JLabel("Card2");
add(label);
}
}

class Card extends JPanel implements ActionListener {

JFrame frame;
final JPanel cards = new JPanel(new CardLayout(20, 20));

void createMainGui() {
/*
* create main frame
*/
frame = new JFrame("Testframe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/*
* add the different cards to the Card Panel (Card Layout)
*/

Card1 card1 = new Card1();
cards.add(card1, "card1");

Card2 card2 = new Card2();
cards.add(card2, "card2");

// Card3 card3 = new Card3();
// cards.add(card3, "card3");

/*
* add the Card panel to the frame, pack it and make it visible
*/
frame.add(cards, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

}

@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}
}

最佳答案

我的代码中的错误是,我从 Card 类扩展了 Card1Card2 类。因此,他们还继承了创建变量cards的方法。在 EventListener 中,引用了错误的 cards 变量(在类 Card1 中创建的变量),因此 EventListener > 不起作用。解决方案:删除Card1Card2中的extend并将EventListener移动到类的内部类中>卡片

private class NewBlaBlaListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//do your stuff here
}
}

并将其添加到 Cards 中的 ActionListenerCard1

card1.addNewBlaBlaListener(new NewBlaBlaListener());

干杯

关于java - CardLayout 不显示下一张卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41457444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com