Search code examples
javajbuttoncardlayout

Cardlayout With Jbutton Not Switching


Hello I am fairly new to java programming and I am currently trying to work on a small game with a GUI, Right now I am stuck at an issue where 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. but for some reason when i use a JButton it does not get switched with the panels. I'm just wondering what I am doing wrong. I am programming as an applet with a IDE called Ready To Program.

{
   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;
   }
}

Solution

  • Frist of all variable names should NOT start with an upper case character. I have never seen a tutorial or answer in any forum that uses an upper case character, so don't make up your own conventions. Learn by example.

    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.

    A JButton is a normal button. What other kind of button are you referring to? It doesn't matter whether the button has text or Icon or both, it is still a button.

    The button in your code doesn't work because you didn't add and ActionListener to the button.

    Read the section from the Swing tutorial on How to Use Button for more information and examples. The tutorial also has a section on How to Write ActionListeners.

    Your code has an action(...) method. I don't know if that is generated by the IDE or not, but basically the code in that method would be the code in your ActionListener.

    add ("Center", AppPanel);
    

    That is not the proper form of the method to add a component to a panel. First all don't use hardcoded literal strings, use the variables provided by the API:

    add (appPanel, BorderLayout.CENTER);