0

I have made a parentPanel that has a CardLayout on it, and under this I've made 4 more JPanel containers.

On the left side I have 4 buttons that when I press "Forside" (button) I want to switch to the panel on the card layout (Forside) and so on...

I've tried different youtube tutorials and tried to look on here without any success. Everything I have tried has ended up with a NullPointerException

public class Main extends JFrame {

    private JPanel contentPane;

    int xx, xy;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setUndecorated(true); // Hides the jframe top bar
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 735, 506);
        contentPane = new JPanel();
        contentPane.setBackground(new Color(102, 102, 102));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel panelLeft = new JPanel();
        panelLeft.setBackground(new Color(51, 51, 51));
        panelLeft.setForeground(Color.DARK_GRAY);
        panelLeft.setBounds(0, 54, 150, 459);
        contentPane.add(panelLeft);
        panelLeft.setLayout(null);

        JButton btnForside = new JButton("Forside");
        btnForside.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

            }
        });
        btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnForside.setForeground(Color.WHITE);
        btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
        btnForside.setContentAreaFilled(false);
        btnForside.setBorderPainted(false);
        btnForside.setBorder(null);
        btnForside.setBounds(16, 60, 112, 30);
        panelLeft.add(btnForside);

        JButton btnDagbog = new JButton("Dagbog");
        btnDagbog.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnDagbog.setContentAreaFilled(false);
        btnDagbog.setBorderPainted(false);
        btnDagbog.setBorder(null);
        btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnDagbog.setForeground(Color.WHITE);
        btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
        btnDagbog.setBounds(16, 116, 112, 30);
        panelLeft.add(btnDagbog);

        JButton btnAftaler = new JButton("Aftaler");
        btnAftaler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnAftaler.setContentAreaFilled(false);
        btnAftaler.setBorderPainted(false);
        btnAftaler.setBorder(null);
        btnAftaler.setForeground(Color.WHITE);
        btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
        btnAftaler.setBounds(16, 173, 112, 30);
        panelLeft.add(btnAftaler);

        JButton btnKontakt = new JButton("Kontakt");
        btnKontakt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnKontakt.setContentAreaFilled(false);
        btnKontakt.setBorder(null);
        btnKontakt.setBorderPainted(false);
        btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnKontakt.setForeground(Color.WHITE);
        btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
        btnKontakt.setBounds(16, 231, 112, 30);
        panelLeft.add(btnKontakt);

        JPanel panelTop = new JPanel();
        panelTop.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent arg0) {
                int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
                int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
                Main.this.setLocation(x - xx, y - xy);  // makes uggerhøj picture dragable
            }
        });
        panelTop.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                 xx = e.getX(); // makes uggerhøj picture dragable
                 xy = e.getY(); // makes uggerhøj picture dragable
            }
        });
        panelTop.setBackground(new Color(51, 51, 51));
        panelTop.setBounds(0, 0, 737, 60);
        contentPane.add(panelTop);
        panelTop.setLayout(null);

        JButton btnX = new JButton("X");
        btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnX.setRolloverIcon(null);
        btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
        btnX.setFocusTraversalKeysEnabled(false);
        btnX.setFocusPainted(false);
        btnX.setBorderPainted(false);
        btnX.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        btnX.setContentAreaFilled(false);
        btnX.setForeground(SystemColor.activeCaption);
        btnX.setBorder(null);
        btnX.setBounds(615, 13, 97, 25);
        panelTop.add(btnX);

        JPanel parentPanel = new JPanel();
        parentPanel.setBackground(Color.GRAY);
        parentPanel.setBounds(148, 54, 569, 405);
        contentPane.add(parentPanel);
        parentPanel.setLayout(new CardLayout(0, 0));

        JPanel Forside = new JPanel();
        parentPanel.add(Forside, "name_1472174211097300");
        Forside.setFocusable(false);

        JButton btnTest = new JButton("test");
        Forside.add(btnTest);

        JPanel Dagbog = new JPanel();
        parentPanel.add(Dagbog, "name_1472176236196000");

        JLabel lblTest = new JLabel("dagbog");
        Dagbog.add(lblTest);


        JPanel Aftaler = new JPanel();
        parentPanel.add(Aftaler, "name_1472177885026100");

        JPanel Kontakt = new JPanel();
        parentPanel.add(Kontakt, "name_1472179607862700");
    }
}

I'd just want it so the right buttons leads to the right cards.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Floofy
  • 1
  • 1) Please use code formatting for code and code snippets, structured documents like HTML/XML or input/output. To do that, select the text and click the `{}` button at the top of the message posting/editing form. 2) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 3) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. .. – Andrew Thompson Apr 25 '19 at 08:54
  • .. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 4) *"Everything I have tried has ended up with a `NullPointerException`"* Hopefully by the time you have carefully read the Q&As related to stack traces and NPE's this next comment will mkae perfect sense. **Always copy/paste error and exception output!** – Andrew Thompson Apr 25 '19 at 08:54
  • 1
    When trying to run your code I get a NullPointerException at this line: btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png"))); Do you also get the NPE here? If so the problem is that the images are not where they should be – Guillaume Apr 25 '19 at 08:58
  • .. 5) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Yes, complete with `import` statements so we can ensure the stack trace here is the equivalent of the stack trace there. Limit it to 2 panels, rather than 4. 6) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson Apr 25 '19 at 09:01
  • It's a GUI so I guess you cant really copy paste the code? I'm trying to figure out how i can swap between my Cards on my CardLayouts, nothing really seems to work – Floofy Apr 25 '19 at 09:05
  • 1
    *"It's a GUI so I guess you cant really copy paste the code?"* I have already copy/pasted the code, added `import` statements. Run it & fixed 4 NPEs (I think @Guillaume nailed it here) and then went on to see no effect on pressing any of the buttons. I have debugged thousands of GUIs and posted MCVEs / SSCCEs of many more. So .. yeah of course I ***can.*** But it's going to take an MCVE / SSCCE from you in order for me to put more effort into this.. – Andrew Thompson Apr 25 '19 at 09:08
  • BTW - I rejected your suggested edit that added the [tag:windowbuilder] again and destroyed all the edits I had made. I suspect that happened because you hit the 'back' button when trying to make an edit. **Don't do that.** Instead use the little [edit] link below the post. But don't re-add the windowbuilder tag. This has little to do with the IDE and much to do with a `NullPointerException`. – Andrew Thompson Apr 25 '19 at 09:12
  • 1
    It would help immensly to know which line of code throws the NPE on your end. And a SSCCE would go a long way in getting an answer here. – Guillaume Apr 25 '19 at 09:22
  • `how i can swap between my Cards on my CardLayouts,` - so why would you create 4 child panels first before doing any testing? The more code you write the harder it is to debug. You should write a little code, then test, then repeat. We are not going to look through 100's of lines of code to spot the 1 line of code that might be wrong. So the solution is start with the working example from the Swing tutorial on [How to Use CardLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html). Modify the code one panel at a time to meet your requirement. – camickr Apr 25 '19 at 14:24

1 Answers1

0

first of all please next time take @AndrewThompson advise about making a MCVE of your code and @camickr advise about the test and debug in little steps before going to the real code (this is the expert programming 101).

the CardLayout object switches between the content of the container via the method

CardLayout.show(Container parent, String name);

keep in mind when making navigation in your swing code DO-NOT make your Components fields in a method instead make it local variables (at least in your case the parentPanel and the CardLayout)

so in order to make your parentPanel switch between your 4 panels (sorry am not familiar with your language) i did a fairly refactored version of your code .


import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class Main extends JFrame {

    private JPanel contentPane;

    int xx, xy;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setUndecorated(true); // Hides the jframe top bar
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 735, 506);
        contentPane = new JPanel();
        contentPane.setBackground(new Color(102, 102, 102));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel Forside = new JPanel();
        JPanel Dagbog = new JPanel();
        JPanel Aftaler = new JPanel();
        JPanel Kontakt = new JPanel();

        JPanel panelLeft = new JPanel();
        panelLeft.setBackground(new Color(51, 51, 51));
        panelLeft.setForeground(Color.DARK_GRAY);
        panelLeft.setBounds(0, 54, 150, 459);
        contentPane.add(panelLeft);
        panelLeft.setLayout(null);

        JButton btnForside = new JButton("Forside");
        btnForside.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                setCardLayoutView("name_1472174211097300");
            }
        });
        btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnForside.setForeground(Color.WHITE);
        btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
        btnForside.setContentAreaFilled(false);
        btnForside.setBorderPainted(false);
        btnForside.setBorder(null);
        btnForside.setBounds(16, 60, 112, 30);
        panelLeft.add(btnForside);

        JButton btnDagbog = new JButton("Dagbog");
        btnDagbog.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setCardLayoutView("name_1472176236196000");
            }
        });
        btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnDagbog.setContentAreaFilled(false);
        btnDagbog.setBorderPainted(false);
        btnDagbog.setBorder(null);
        btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnDagbog.setForeground(Color.WHITE);
        btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
        btnDagbog.setBounds(16, 116, 112, 30);
        panelLeft.add(btnDagbog);

        JButton btnAftaler = new JButton("Aftaler");
        btnAftaler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setCardLayoutView("name_1472177885026100");
            }
        });
        btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnAftaler.setContentAreaFilled(false);
        btnAftaler.setBorderPainted(false);
        btnAftaler.setBorder(null);
        btnAftaler.setForeground(Color.WHITE);
        btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
        btnAftaler.setBounds(16, 173, 112, 30);
        panelLeft.add(btnAftaler);

        JButton btnKontakt = new JButton("Kontakt");
        btnKontakt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setCardLayoutView("name_1472179607862700");
            }
        });
        btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnKontakt.setContentAreaFilled(false);
        btnKontakt.setBorder(null);
        btnKontakt.setBorderPainted(false);
        btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
        btnKontakt.setForeground(Color.WHITE);
        btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
        btnKontakt.setBounds(16, 231, 112, 30);
        panelLeft.add(btnKontakt);

        JPanel panelTop = new JPanel();
        panelTop.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent arg0) {
                int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
                int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
                Main.this.setLocation(x - xx, y - xy);  // makes uggerhøj picture dragable
            }
        });
        panelTop.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xx = e.getX(); // makes uggerhøj picture dragable
                xy = e.getY(); // makes uggerhøj picture dragable
            }
        });
        panelTop.setBackground(new Color(51, 51, 51));
        panelTop.setBounds(0, 0, 737, 60);
        contentPane.add(panelTop);
        panelTop.setLayout(null);

        JButton btnX = new JButton("X");
        btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnX.setRolloverIcon(null);
        btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
        btnX.setFocusTraversalKeysEnabled(false);
        btnX.setFocusPainted(false);
        btnX.setBorderPainted(false);
        btnX.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        btnX.setContentAreaFilled(false);
        btnX.setForeground(SystemColor.activeCaption);
        btnX.setBorder(null);
        btnX.setBounds(615, 13, 97, 25);
        panelTop.add(btnX);

        parentPanel = new JPanel();
        parentPanel.setBackground(Color.GRAY);
        parentPanel.setBounds(148, 54, 569, 405);
        contentPane.add(parentPanel);
        cardLayoutObject = new CardLayout(0, 0);
        parentPanel.setLayout(cardLayoutObject);

        parentPanel.add(Forside, "name_1472174211097300");
        Forside.setFocusable(false);

        JButton btnTest = new JButton("test");
        Forside.add(btnTest);

        parentPanel.add(Dagbog, "name_1472176236196000");

        JLabel lblTest = new JLabel("dagbog");
        Dagbog.add(lblTest);

        parentPanel.add(Aftaler, "name_1472177885026100");

        parentPanel.add(Kontakt, "name_1472179607862700");
    }
    private CardLayout cardLayoutObject;
    private JPanel parentPanel;

    private void setCardLayoutView(String viewName) {
        cardLayoutObject.show(parentPanel, viewName);
    }

}

and happy coding ^-^.

OverLoadedBurden
  • 606
  • 1
  • 5
  • 14