java - Jbutton 不切换的卡片布局

标签 java jbutton cardlayout

你好,我对java编程相当陌生,我目前正在尝试使用GUI开发一个小游戏,现在我遇到了一个问题,我只能使用带有卡片布局的普通按钮,不幸的是我想使用我自己的带有按钮的图标,为此我需要使用JButton。但由于某种原因,当我使用 JButton 时,它不会与面板切换。我只是想知道我做错了什么。我正在使用名为 Ready To Program 的 IDE 作为小程序进行编程。

{
   CardLayout PanelLayout = new CardLayout ();
   JPanel AppPanel = new JPanel (); //Main App Panel using cardlayout

   JPanel StartPanel = new JPanel (); //Start Menu Panel
   JPanel GamePanel = new JPanel (); //Running Game Panel

   JButton StartBtn = new JButton ();

   public void init ()
   {


      StartBtn.setIcon(new ImageIcon ("StartIcon.png"));
      StartBtn.setBorder(BorderFactory.createEmptyBorder());
      StartBtn.setContentAreaFilled(true);

      StartPanel.add (StartBtn);

      AppPanel.setLayout (PanelLayout);

      AppPanel.add (StartPanel, "1");
      AppPanel.add (GamePanel, "2");

      PanelLayout.show (AppPanel, "1");

      setLayout (new BorderLayout ());
      add ("Center", AppPanel);
   }


   public boolean action (Event e, Object o)
   {
      if (e.target == StartBtn)
      {
         PanelLayout.show (AppPanel, "2");
      }
      return true;
   }
}

最佳答案

所有变量名称首先不应以大写字符开头。我从未在任何论坛上看到过使用大写字符的教程或答案,所以不要制定自己的约定。通过示例学习。

I can only use a normal button with a card layout, unfortunately I want to use my own icon with the button and to do this I need to use a JButton.

JButton 是一个普通按钮。您指的是哪种其他类型的按钮?无论按钮是否有文本或图标或两者都有,它仍然是一个按钮。

代码中的按钮不起作用,因为您没有向按钮添加 ActionListener。

阅读 Swing 教程中关于 How to Use Button 的部分了解更多信息和示例。本教程还有一个关于如何编写 ActionListeners 的部分。

您的代码有一个 action(...) 方法。我不知道它是否是由 IDE 生成的,但基本上该方法中的代码就是 ActionListener 中的代码。

add ("Center", AppPanel);

这不是将组件添加到面板的方法的正确形式。首先不要使用硬编码的文字字符串,使用 API 提供的变量:

add (appPanel, BorderLayout.CENTER);

关于java - Jbutton 不切换的卡片布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352333/

相关文章:

java - 我可以在 CardLayout 中设置单个面板的大小吗?

java - Java list 中的换行符

java - 如何为所有实体定义 allocationSize 和 initialValue

java - 如何获取 Android 用户的电子邮件地址?

Java - 无法加载相同的 url 并将其显示在编辑器 Pane 中两次?

java - JButton 错误无法应用于给定类型

java - 如何让字符串显示在 jLabel 中?

java - 延迟初始化启用了 CardLayout?

java - Spring /Java 邮件 : The FROM address is being ignored

java - 将 CardLayout 与 JTable 一起使用,并且 JTable.getSelectedRow() 始终返回 -1