试图让cardLayout工作

时间:2015-06-22 02:36:42

标签: java swing awt layout-manager cardlayout

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

我有这个,我觉得它应该完全奏效,但是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 extends JFrame实现了ActionListener        ^ 如果有人可以给我一个提示,那将非常感激!!

1 个答案:

答案 0 :(得分:2)

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

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