问题描述
我有两个JPanel,我希望在用户单击它们时在它们之间切换.
I have two JPanels that I want to switch between when user clicks on them.
所以我创建了一个带有JFrame
的Window
.然后创建一个名为cards
的JPanel
并将其布局设置为CardLayout
.然后,我再创建两个JPanel
-这些是我要在它们之间切换的面板-然后将它们添加到cards
中.我添加了mouseClicked
事件侦听器,并添加了cardLayout.next(cards)
,因此切换将会发生.这是行不通的.
So I created a Window
with a JFrame
in it. Then I create a JPanel
called cards
and set its layout to CardLayout
. Then I create two more JPanel
s - these are the panels that I want to switch between - and I add them to cards
. I add mouseClicked
event listeners and I add cardLayout.next(cards)
so the switch will happen. It doesn't work.
这是我的代码:
public class Window {
private JFrame frame;
private JPanel cards;
private JPanel panel1;
private JPanel panel2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 790, 483);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cards = new JPanel();
cards.setLayout(new CardLayout());
panel1 = new JPanel();
panel1.setBackground(Color.BLACK);
panel1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
});
panel2 = new JPanel();
panel2.setBackground(Color.WHITE);
panel1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
});
cards.add(panel1, "panel1");
cards.add(panel2, "panel2");
frame.getContentPane().add(cards);
}
}
为什么不起作用?
推荐答案
您已经在同一面板中添加了2个MouseListeners
,这实际上取消了对CardLayout.next
的调用.替换其中一个
You've added 2 MouseListeners
to the same panel which effectively cancels out the call to CardLayout.next
. Replace one of
panel1.addMouseListener(new MouseAdapter() {
与
panel2.addMouseListener(new MouseAdapter() {
这篇关于如何在CardLayout中的JPanels之间切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!