试图让 cardLayout 工作

Attempting to get cardLayout to work

我想要做的就是设置卡片布局样式按钮。从理论上讲,您应该点击按钮,然后另一个(在本例中)名称会出现,直到完成。 (当用户要关闭时)

我有这个,我觉得它应该完全有效,但是 JGrasp 给我一个错误:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JDisappearingFriends extends JFrame implements ActionListener
{
   private JButton intro = new JButton("Click to see Friends!");
   private JButton nb = new JButton("Mini Vinny");
   private JButton sb = new JButton("Makayla");
   private JButton eb = new JButton("Aurora");
   private JButton wb = new JButton("Alyssa");
   private JButton cb = new JButton("And My Bestest Friend: SAMMY!!");
   CardLayout cardLayout = new CardLayout();
   public JDisappearingFriends()
   {
      setLayout(new CardLayout());
      add("Click to see Friends!", intro);
      add("MiniVinny", nb);
      add("Makayla", sb);
      add("Aurora", eb);
      add("Alyssa", wb);
      add("And Finally My Best Friend Sammy!", cb);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      intro.addActionListener(this);
      nb.addActionListener(this);
      sb.addActionListener(this);
      eb.addActionListener(this);
      wb.addActionListener(this);
   }
   public void actionPreformed(ActionEvent e)
   {
      cardLayout.next(getContentPane());
   }
   public static void main(String[] args)
   {
      JDisappearingFriends jbl = new JDisappearingFriends();
      jbl.setSize(400, 400);
      jbl.setVisible(true);
   }
}

当我尝试编译时,收到一条错误消息,如下所列:

JDisappearingFriends.java:8: error: JDisappearingFriends is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener

public class JDisappearingFriends 扩展 JFrame 实现 ActionListener ^ 如果有人可以给我提示,将不胜感激!!

您的错误消息很好地说明了问题所在:

JDisappearingFriends.java:8: error: JDisappearingFriends is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener

actionPreformed 拼错了,应该是 actionPerformed

你也应该习惯使用 @Override 注释

@Override
public void actionPreformed(ActionEvent e)
{
    cardLayout.next(getContentPane());
}

这在您重写其他方法时会有所帮助 类 并提供编译时间保护以确保您不会不小心拼错方法名称

您还应该在 EDT 的上下文中创建您的 UI。有关详细信息,请参阅 Initial Threads