1

Now I know there are many, many questions on this and I've read a dozen. But I've just hit a wall, I can't make heads or tails of it.

Heres my question.

I have 3 Panel classes.

ConfigurePanel.java
ConnectServerPanel.java
RunServerPanel.java

and my JFrame class

StartUPGUI.java

This is what is initialised at startup

private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    startUp = new sjdproject.GUI.ConfigurePanel();
    runServer = new sjdproject.GUI.RunServerPanel();
    serverConnect = new sjdproject.GUI.ConnectServerPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

    jPanel1.setLayout(new java.awt.CardLayout());
    jPanel1.add(startUp, "card2");
    jPanel1.add(runServer, "card4");
    jPanel1.add(serverConnect, "card3");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(27, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(38, 38, 38))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(27, 27, 27)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(30, Short.MAX_VALUE))
    );

My StartUPGUI calls the StartUpPanel first. In my StartUpPanel.java I have a button which calls the setPanel method in StartUPGUI

    StartUpGUI s = new StartUpGUI(); 
    String str = "";
    if(runserverbtn.isSelected()){
         str =  "runserver";
    }
    else if(connectserverbtn.isSelected()){
        str = "connectserver";
    }
    else{
        str = "";
    }
    s.setPanel(str);

Here is my setPanel method

void setPanel(String str){
     if(str == "runserver"){

    }
    else if(str == "connectserver"){

    }

    else{
    }
}

What do I need to put inside the if blocks to change panel views? I would have assumed jPanel1.something() but I don't know what that something is.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
ragingbull
  • 119
  • 1
  • 2
  • 8

1 Answers1

5

"What do I need to put inside the if blocks to change panel views? I would have assumed jPanel1.something() but I don't know what that something is."

  1. Don't compare string with ==, it will not work. Use .equals.. if("runserver".equals(str)){

  2. You need to use the method .show from the CardLayout

    CardLayout.show(jPanel1, "whichPanel");
    
    • public void show(Container parent, String name) - Flips to the component that was added to this layout with the specified name, using addLayoutComponent. If no such component exists, then nothing happens.

      void setPanel(String str){
          CardLayout layout = (CardLayout)jPanel1.getLayout();
          if("runserver".equals(str)){
              layout.show(jPanel1, "card4");
      
          }else if("connectserver".equals(str)){
             layout.show(jPanel1, "card3");
      
          } else{
              layout.show(jPanel1, "card2");
          }
      }
      

See How to Use CardLayout for more details and see the API for more methods.


UPDATE

Try running this example and examine it with your code to see if you notice anything that will help

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestCardLayout {

    PanelOne p1 = new PanelOne();
    PanelTwo p2 = new PanelTwo();
    PanelThree p3 = new PanelThree();

    CardLayout layout = new CardLayout();
    JPanel cardPanel = new JPanel(layout);

    public TestCardLayout() {
        JButton showOne = new JButton("Show One");
        JButton showTwo = new JButton("Show Two");
        JButton showThree = new JButton("Show Trree");
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.add(showOne);
        buttonsPanel.add(showTwo);
        buttonsPanel.add(showThree);
        showOne.addActionListener(new ButtonListener());
        showTwo.addActionListener(new ButtonListener());
        showThree.addActionListener(new ButtonListener());

        cardPanel.add(p1, "panel 1");
        cardPanel.add(p2, "panel 2");
        cardPanel.add(p3, "panel 3");

        JFrame frame = new JFrame("Test Card");
        frame.add(cardPanel);
        frame.add(buttonsPanel, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if ("Show One".equals(command)) {
                layout.show(cardPanel, "panel 1");
            } else if ("Show Two".equals(command)) {
                layout.show(cardPanel, "panel 2");
            } else {
                layout.show(cardPanel, "panel 3");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestCardLayout testCardLayout = new TestCardLayout();
            }
        });
    }
}

class PanelOne extends JPanel {

    public PanelOne() {
        setBackground(Color.GREEN);
        add(new JLabel("Panel one"));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }
}

class PanelTwo extends JPanel {

    public PanelTwo() {
        setBackground(Color.BLUE);
        add(new JLabel("Panel two"));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }
}

class PanelThree extends JPanel {

    public PanelThree() {
        setBackground(Color.YELLOW);
        add(new JLabel("Panel three"));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }
}

UPDATE 2

The problem is, the the button is in the ConfigurePanel class. Trying to create a new StartUPGUI in that class, won't reference the same components. What you need to do is pass a reference of the StartUPGUI to the ConfigurePanel. Something like this

    public class ConfigurePanel extends JPanel {
        StartUPGUI startup;

        public ConfigurePanel(StartUPGUI startup) {
            this.startup = startup;
        }

        ....
        public void actionPerformed(ActionEvent e) {
            startup.setPanel("runserver");

        }
    }

And instantiate ConfigurePanel from the StartUPGUI like this

    new ConfigurePanel(StartUPGUI.this);
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Well, it didnt crash or throw an exception. But nothing happened. I tried **layout.show(jPanel1, "card4");**. Does this mean the (runServer, "card4") component does not exist? Why would this be – ragingbull Jan 29 '14 at 06:34
  • Where _exactly_ is the code from the second code block of your post? I mean where does it exist in your program code? The code I have should always work, given you're using it in the correct manner and context. – Paul Samsotha Jan 29 '14 at 06:37
  • I see `.jPanel1.add(runServer, "card")` in your code, so it _does_ exist. – Paul Samsotha Jan 29 '14 at 06:38
  • StartUPGUI.java class is the JFrame and holds the setPanel() and initComponents() methods. The setPanel() method is called in a button click in the ConfigurePanel.java class – ragingbull Jan 29 '14 at 06:44
  • Hey I have to step out for a couple hours. Try running the example in by edit and see if you can gain anything from it. When I get back I'll try and examine your situation further. – Paul Samsotha Jan 29 '14 at 06:59
  • It works as a class of its own. So there's no bugs in my system if that was the test. – ragingbull Jan 29 '14 at 09:17
  • It wasn't a test. It was to show you how it works, and maybe you could pick something up from it. But anyway, you should be looking at the second update. I'm sure that's where your problem is, creating a `new StartUPGUI` in your `CongifurePanel` class. You want to actually reference the same one by passing it as a reference – Paul Samsotha Jan 29 '14 at 09:25
  • Ok, where do i instantiate the **new ConfigurePanel(StartUPGUI.this);**. I ask because i cant put it in the initComponents() method as new ConfigurePanel() has been auto coded in by netbeans. – ragingbull Jan 29 '14 at 09:59
  • I'm not totally sure how you added those components as drag an drop components, but What I do is just do it in the constructor of _after_ the `initComponents` You can do that with _all_ your panels that are from other java files. That's how I normally do it. BTW, how _did_ you add them as drag and drop components? Just for _my_ future reference. – Paul Samsotha Jan 29 '14 at 10:02
  • I set a main jPanel in the jFrame. I set the jPanel too cardlayout, and then just copied my jPanel classes to the main jPanel. – ragingbull Jan 29 '14 at 10:06
  • Wait, you mean copy and pasted? How was the code auto-generated. I assuming only dragging and dropping auto-generates the code – Paul Samsotha Jan 29 '14 at 10:07
  • At **startup.setPanel("runserver");** im getting a **Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException** – ragingbull Jan 29 '14 at 10:09
  • So you only have _one_ java file then, and not the 4 your post suggests. – Paul Samsotha Jan 29 '14 at 10:12
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46326/discussion-between-peeskillet-and-ragingbull) – Paul Samsotha Jan 29 '14 at 10:12