【问题标题】:Attempting to get cardLayout to work试图让 cardLayout 工作
【发布时间】:2015-09-07 09:37:50
【问题描述】:

我要做的只是设置卡片布局样式按钮。从理论上讲,您应该单击按钮,并且假设会出现另一个(在这种情况下)名称,直到完成。 (当用户关闭时)

我有这个,我觉得它应该完全可以工作,但是 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

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

【问题讨论】:

    标签: java swing awt layout-manager cardlayout


    【解决方案1】:

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

    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

    【讨论】:

    • 哈哈哈哈哈哈哈哈天哪,太感谢你了,我不敢相信就这么简单!!!!看得太疯狂了!!谢谢,现在我可以停止敲键盘了!
    • @Stuckonsameproblem 哦,我不知道,我发现把头靠在键盘上往往会写出更好的代码;)
    猜你喜欢
    • 2019-02-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2011-10-02
    • 2015-10-21
    相关资源
    最近更新 更多