Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Removing a JPanel from another class

  1. #1
    Member
    Join Date
    Mar 2013
    Posts
    47
    My Mood
    Amused
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Question Removing a JPanel from another class

    Hello everyone, I have once again aproached a problem on my journey to Java.

    What I want to do:
    I want to be able to remove a Jpanel from the main class but with another class. I'll try to show you what I mean:

    The main class code:
    package tictactoe;
    import javax.swing.JFrame;
     
     
     
    public class TicTacToe extends JFrame{
     
        public static void main(String[] args) {
     
     
            TheFrame window = new TheFrame();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setSize(966,600);
            TheActualMenu menu = new TheActualMenu();
            window.addPanel(menu);
            window.setResizable(false);
            window.setVisible(true);
        }
     
     
    }



    the "TheFrame" code:
    package tictactoe;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
     
     
     
     
    public class TheFrame extends JFrame{
     
     
     
     
     
        public TheFrame(){
            super("Tic tac toe");
        }
     
     
        public void addPanel(JPanel panel){
            add(panel);
        }
     
        public void removePanel(JPanel panel){
            remove(panel);
        }
     
     
     
    }


    The class where the removing should happen, class TheActualMenu:
    package tictactoe;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.awt.Image;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ImageIcon;
     
     
     
    public class TheActualMenu extends JPanel{
        private Image background;
        private Image StartNormalState;
        private Image StartMouseHover;
        private Image StartPressed;
        private Image imageState;
     
     
     
     
     
        public TheActualMenu(){
     
            Handler theHandler = new Handler();
     
        }
     
     
     
     
     
     
     
     
        class Handler extends MouseAdapter{
     
     
     
            public Handler(){
     
     
            addMouseListener(new MouseAdapter(){
                @Override
                public void mouseClicked(MouseEvent e){
                    if(e.getX() >= (966/2)-(imageState.getWidth(null)/2) 
                            && e.getX() <= (966/2)+(imageState.getWidth(null)/2) 
                            && e.getY() >= 32 && e.getY() <= 32+imageState.getHeight(null)){
     
                        //Event where The menu panel in TicTacToe gets removed
     
                    }
     
                }
            });
     
     
     
     
     
     
            }
     
        }
     
     
    }








    I can't do TheFrame.removePanel(menu); since it's a JFrame and the constructor will create a new frame.


    What should I do?

    I hope this made sence and that the code isn't to sloppy.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Removing a JPanel from another class

    No, what you're trying to do is not clear. If you want to replace one JPanel with another, alternating between them as needed, you should check out CardLayout.

  3. #3
    Member
    Join Date
    Mar 2013
    Posts
    47
    My Mood
    Amused
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Removing a JPanel from another class

    Sorry it took me a while to respond(my internet was just too slow)

    Okey looked at the cardlayout functions, found an example, and now I have this:

    main code:
    package tictactoe;
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
     
     
     
    public class TicTacToe extends JFrame{
        public CardLayout cardlayout = new CardLayout();
        private static JPanel cardPanel, jp1, jp2, buttonPanel;
        private JLabel jl1, jl2;
        private JButton btn1, btn2;
        private static TheActualMenu menu = new TheActualMenu();
        private WindowMenu gameSession;
     
        public TicTacToe(){
            super("Tica taca toa");
     
            HandlerMenu handling = new HandlerMenu();
            menu = new TheActualMenu();
            gameSession = new WindowMenu();
     
            cardPanel = new JPanel();
            cardPanel.setLayout(cardlayout);
            jp1 = new JPanel();
            jp2 = new JPanel();
            jl1 = new JLabel("Card 1");
            jl2 = new JLabel("Card 2");
            buttonPanel = new JPanel();
            jp1.add(menu);
            jp2.add(gameSession);
            cardPanel.add(menu, "1");
            cardPanel.add(gameSession, "2");
            cardlayout.show(cardPanel, "1");
            btn1 = new JButton("Show Card 1");
     
            btn1.addActionListener(new ActionListener(){
                @Override
               public void actionPerformed(ActionEvent e){
                   //cardlayout.show(cardPanel, "1");
                   cardlayout.show(cardPanel, "1");
               } 
            });
     
     
     
     
            btn2 = new JButton("Show Card 2");
            btn2.addActionListener(new ActionListener(){ 
                @Override
                public void actionPerformed(ActionEvent e){
                    //cardlayout.show(cardPanel, "2");
                    changeToGame();
                }
            });
     
     
     
            buttonPanel.add(btn1);
            buttonPanel.add(btn2);
            add(buttonPanel, BorderLayout.SOUTH);
     
     
     
     
     
     
     
     
     
     
     
     
     
     
        }
     
     
        public void changeToGame(){
            cardlayout.show(cardPanel, "2");
        }
     
     
     
     
     
        public static void main(String[] args) {   
            EventQueue.invokeLater(new Runnable(){
     
     
     
            @Override
            public void run(){
              TicTacToe frame = new TicTacToe();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(966,600);
              frame.add(cardPanel);
              frame.setVisible(true);
            }});
     
     
        }
     
     
     
     
     
     
        class HandlerMenu extends MouseAdapter{
     
            public HandlerMenu(){
            addMouseListener(new MouseAdapter(){
                @Override
                public void mouseClicked(MouseEvent e){
                    /*if(e.getX() >= (966/2)-(240/2) 
                            && e.getX() <= (966/2)+(240/2) 
                            && e.getY() >= 32 && e.getY() <= 131){*/
                        System.out.println("Now");
                        //changeToGame();
     
                    //}
     
                }
            });
     
            }
     
        }
     
     
     
     
     
     
     
        }
     
     
     
    The "the frame" code


    the "TheFrame" code:
    package tictactoe;
    import java.awt.CardLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
     
     
     
     
    public class TheFrame extends JFrame{
        private CardLayout cardLayout = new CardLayout();
        private JPanel cardPanel, jp1, jp2;
        private TheActualMenu menu;
        private WindowMenu gameSession;
     
     
        public TheFrame(){
            super("Tic tac toe");
     
            cardPanel = new JPanel();
            cardPanel.setLayout(cardLayout);
            jp1 = new JPanel();
            jp2 = new JPanel();
            menu = new TheActualMenu();
            jp1.add(menu);
            gameSession = new WindowMenu();
            jp2.add(gameSession);
            cardPanel = new JPanel();
            cardPanel.add(jp1, "1");
            cardPanel.add(jp2, "2");
            cardLayout.show(cardPanel, "1");
     
     
     
            add(cardPanel);
        }
     
     
        public void addPanel(JPanel panel){
            add(panel);
        }
     
        public void removePanel(JPanel panel){
            remove(panel);
        }
     
     
     
     
     
     
    }


    and the "Theactualmenu" class:
    package tictactoe;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.awt.Image;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ImageIcon;
     
     
     
    public class TheActualMenu extends JPanel{
        private Image background;
        private Image StartNormalState;
        private Image StartMouseHover;
        private Image StartPressed;
        private Image imageState;
     
     
     
     
     
     
        public TheActualMenu(){
            background = new ImageIcon("C:\\Users\\Elias Fredin\\Desktop\\placeholder\\TicTacToe\\TicTacToe\\src\\tictactoe\\TTTBackground.png").getImage();
            StartNormalState = new ImageIcon("C:\\Users\\NAME\\Desktop\\placeholder\\TicTacToe\\TicTacToe\\src\\tictactoe\\StartNotPressed.png").getImage();
            StartMouseHover = new ImageIcon("C:\\Users\\NAME\\Desktop\\placeholder\\TicTacToe\\TicTacToe\\src\\tictactoe\\StartMouseHover.png").getImage();
            StartPressed = new ImageIcon("C:\\Users\\NAME\\Desktop\\placeholder\\TicTacToe\\TicTacToe\\src\\tictactoe\\StartMousePressed.png").getImage();
            imageState = StartNormalState;
     
     
            Handler theHandler = new Handler();
     
        }
     
     
        @Override
        public void paint(Graphics g){
            super.paint(g);
            g.drawImage(background, 0, 0, null);
            g.drawImage(imageState, (966/2)-(imageState.getWidth(this)/2), 32, null);
        }
     
     
     
     
     
        class Handler extends MouseAdapter{
     
     
     
            public Handler(){
     
     
            addMouseMotionListener(new MouseAdapter(){ 
                @Override
                public void mouseMoved(MouseEvent e){
                    if(e.getX() >= (966/2)-(imageState.getWidth(null)/2) 
                            && e.getX() <= (966/2)+(imageState.getWidth(null)/2) 
                            && e.getY() >= 32 && e.getY() <= 32+imageState.getHeight(null)){
                    imageState = StartMouseHover;
                    repaint();
                    }
                    else
                    {
                    imageState = StartNormalState;
                    repaint();
                    }
                }
            });
     
            addMouseListener(new MouseAdapter(){
                @Override
                public void mousePressed(MouseEvent e){
                    if(e.getX() >= (966/2)-(imageState.getWidth(null)/2) 
                            && e.getX() <= (966/2)+(imageState.getWidth(null)/2) 
                            && e.getY() >= 32 && e.getY() <= 32+imageState.getHeight(null)){
                        imageState = StartPressed;
                        repaint();
                    }
                }
            });
     
     
            addMouseListener(new MouseAdapter(){
                @Override
                public void mouseClicked(MouseEvent e){
                    if(e.getX() >= (966/2)-(imageState.getWidth(null)/2) 
                            && e.getX() <= (966/2)+(imageState.getWidth(null)/2) 
                            && e.getY() >= 32 && e.getY() <= 32+imageState.getHeight(null)){
     
                        System.out.println(imageState.getHeight(null));//Event where the JPanel switch should happen
     
                    }
     
                }
            });
     
     
            }
     
        }
     
     
     
     
    }


    SO now It works to switch between the panels by pressing the buttons, but how to I switch the pannels, by using the "changeToGame" function, from the class "TheActualFrame"?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Removing a JPanel from another class

    The class responsible for displaying panels should have a method to change it's state, (switch panels). This method would be invoked when the time comes to switch panels. Call the method from where ever is needed, ("TheActualFrame").

  5. #5
    Member
    Join Date
    Mar 2013
    Posts
    47
    My Mood
    Amused
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Removing a JPanel from another class

    I created the method "changeToGame()" in the class "TicTacToe" but I can't manage to acces it through other classes.

    I can't do: TicTacToe tac = new TicTacToe();

    tac.changeTogame();

    since it would execute whats in the constructor.

    Even if I create a new class with all the cardPanel content in it I'll still have to call it with: theCardPanelname CradPanels = new theCardPanelname();
    and everything in the constructor gets executed.

    And I tried to that but to use a method instead of the constructor and call that instead when adding it to the JFrame, but I failed :/

    But I can't really say that it doesn't work since I'm a noob. Any advice?

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Removing a JPanel from another class

    Quote Originally Posted by kinkita View Post
    I created the method "changeToGame()" in the class "TicTacToe" but I can't manage to acces it through other classes.
    Why not? What did you try? What happened? ...Post the code so we can filter through it.

    Quote Originally Posted by kinkita View Post
    And I tried to that but to use a method instead of the constructor and call that instead when adding it to the JFrame, but I failed :/
    But I can't really say that it doesn't work since I'm a noob. Any advice?
    Yes, use a method. Again post what you have tried, what happened, and what you want to happen.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Removing a JPanel from another class

    Your post doesn't make sense. If changeToGame() is a TicTacToe method, then tac.changeToGame() HAS to work and should have nothing to do with the constructor.

    If you want one class to be aware of an instance of another class, you could always use a setter. For example, if an instance of CardPanels needs to be aware of a specific instance of TicTacToe, you could use a CardPanels method like:
    setTicTacToeInstance( TicTacToe tic )
    {
        this.tic = tic;
    }
    Or you could pass it to a CardPanels() constructor:
    public CardPanel( TicTacToe tic )
    {
        this.tic = tic;
     
        // etc., the rest of the constructor . . .
    }

  8. #8
    Member
    Join Date
    Mar 2013
    Posts
    47
    My Mood
    Amused
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Removing a JPanel from another class

    I managed to acces the class method "changeToGame". I added a System.out text to see if it worked and it did, but when I add the code "cardlayout.show(cardPanel, "2");" this error message comes up:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout
    at java.awt.CardLayout.checkLayout(CardLayout.java:38 4)
    at java.awt.CardLayout.show(CardLayout.java:506)
    at tictactoe.TicTacToe.setCurrentPanel(TicTacToe.java :79)
    at tictactoe.TheActualMenu$Handler$3.mouseClicked(The ActualMenu.java:96)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEvent Multicaster.java:253)
    at java.awt.Component.processMouseEvent(Component.jav a:6300)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3275)
    at java.awt.Component.processEvent(Component.java:606 2)
    at java.awt.Container.processEvent(Container.java:203 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4660)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2097)
    at java.awt.Component.dispatchEvent(Component.java:44 88)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4575)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4245)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4166)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2083)
    at java.awt.Window.dispatchEventImpl(Window.java:2489 )
    at java.awt.Component.dispatchEvent(Component.java:44 88)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:674)
    at java.awt.EventQueue.access$400(EventQueue.java:81)
    at java.awt.EventQueue$2.run(EventQueue.java:633)
    at java.awt.EventQueue$2.run(EventQueue.java:631)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:647)
    at java.awt.EventQueue$3.run(EventQueue.java:645)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 644)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Removing a JPanel from another class

    Cross posted here at DIC.

    It's difficult to help you without seeing updated code, preferably something that can be run, an SSCCE, that demonstrates the problem. Show us enough code to help you, the code the error refers to at a minimum. Otherwise, what would you expect us to do?

    Taking a stab at your error message, "wrong parent for CardLayout," suggests you're mixing the parent and child relationship between the main container - the parent - and the cards it contains. For example, if you have two cards you want to alternate, there should be a third container in which to show the cards, the parent, to which the cards belong.

    --- Update ---

    In spite of my bluster, I took the code you posted at the other site and reduced it to something that could be run. Unfortunately, in the process I eliminated the error you've complained about and, in fact, never saw it. I also stripped the code of any real functionality other than switching between the two cards which have been given different colors to show the change. You might try adding your functionality back to the runnable framework I've provided, fixing breaks (if any) as you go. Starting with a bare bones framework and adding the desired functionality to it is a reasonable approach to building any complex project, providing a simple "test and fix" platform as you build. I recommend you try a similar approach for your next project. Let me know if you have any questions.
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    public class TicTacToe extends JFrame
    {
        public CardLayout cardlayout = new CardLayout();
        public static JPanel cardPanel, buttonPanel;
        private JButton btn1, btn2;
        public TheActualMenu menu;
        public JPanel gameSession;
        public TicTacToe taca;
     
        // the default constructor
        // got rid of IniTicTacToe as I'm not sure of its purpose
        public TicTacToe()
        {
            // close the program when the TicTacToe frame is closed and
            // set other characteristics
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            setLocationRelativeTo( null );
            setSize(966,600);
     
            // create the first card
            menu = new TheActualMenu();
            menu.setOpaque( true );
            menu.setBackground( Color.RED );
     
            // create the second card
            gameSession = new JPanel();
            gameSession.setOpaque( true );
            gameSession.setBackground( Color.BLUE );
     
     
            cardPanel = new JPanel();
            cardPanel.setLayout(cardlayout);
            buttonPanel = new JPanel();
            cardPanel.add(menu, "1");
            cardPanel.add(gameSession, "2");
            cardlayout.show(cardPanel, "1");
     
            add(cardPanel);
     
            btn1 = new JButton("Show Card 1");
            btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e){
                    cardlayout.show(cardPanel, "1");
                } 
            });
     
            btn2 = new JButton("Show Card 2");
            btn2.addActionListener(new ActionListener(){ 
                @Override
                public void actionPerformed(ActionEvent e){
                    setCurrentPanel();
                }
            });
     
            buttonPanel.add(btn1);
            buttonPanel.add(btn2);
            add(buttonPanel, BorderLayout.SOUTH);
     
        } // end method IniTicTacToe()
     
        public void setCurrentPanel()
        {
            cardlayout.show(cardPanel, "2");
            System.out.println("It's working");
     
        } // end method setCurrentPanel()
     
        public static void main(String[] args)
        {   
            TicTacToe tictac = new TicTacToe();
     
            // moved the next two lines into the constructor
            //        tictac.add(cardPanel);
            //        tictac.setSize(966,600);
            tictac.setVisible(true);
     
        } // end method main()
     
    } // end class TicTacToe
     
    // I stripped this down to nothing, but you can fill back in as needed
    class TheActualMenu extends JPanel
    {
        public TheActualMenu()
        {
            // this statement causes an infinite loop, so has been commented out
            //        Handler theHandler = new Handler();
        }
     
     
        @Override
        public void paint(Graphics g)
        {
            super.paint(g);
        }
     
        class Handler extends MouseAdapter
        {
            private TicTacToe tac;
     
     
            public Handler()
            {
                // this sets up the infinite loop, and I'm not sure of its purpose
                tac = new TicTacToe();
     
                addMouseMotionListener(new MouseAdapter()
                { 
                    @Override
                    public void mouseMoved(MouseEvent e)
                    {
                    }
                });
     
                addMouseListener(new MouseAdapter()
                {
                    @Override
                    public void mousePressed(MouseEvent e)
                    {
                    }
                });
     
     
     
                addMouseListener(new MouseAdapter()
                {
                    @Override
                    public void mouseClicked(MouseEvent e)
                    {
                    }
                });
     
            } // end constructor
     
        } // end class Handler
     
    } // end class TheActualMenu

  10. #10
    Member
    Join Date
    Mar 2013
    Posts
    47
    My Mood
    Amused
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Removing a JPanel from another class

    Yes that works but the problem I am having is changing the cardlayout from another class, that is a different file.

    I modifyed your code.

    main code
    package cardlayouttest;
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    public class CardlayoutTest extends JFrame
    {
        public CardLayout cardlayout = new CardLayout();
        public static JPanel cardPanel, buttonPanel;
        private JButton btn1, btn2;
        public JPanel gameSession;
        public CardlayoutTest taca;
        public panel thePanel;
        public panelTwo theSecondPanel;
     
        // the default constructor
        // got rid of IniTicTacToe as I'm not sure of its purpose
        public CardlayoutTest()
        {
            // close the program when the TicTacToe frame is closed and
            // set other characteristics
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            setLocationRelativeTo( null );
            setSize(966,600);
     
            // create the first card
            thePanel = new panel();
            thePanel.setOpaque( true );
            thePanel.setBackground( Color.RED );
     
            // create the second card
            theSecondPanel = new panelTwo();
            theSecondPanel.setOpaque( true );
            theSecondPanel.setBackground( Color.BLUE );
     
     
            cardPanel = new JPanel();
            cardPanel.setLayout(cardlayout);
            buttonPanel = new JPanel();
            cardPanel.add(thePanel, "1");
            cardPanel.add(theSecondPanel, "2");
            cardlayout.show(cardPanel, "1");
     
            add(cardPanel);
     
            btn1 = new JButton("Show Card 1");
            btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e){
                    cardlayout.show(cardPanel, "1");
                } 
            });
     
            btn2 = new JButton("Show Card 2");
            btn2.addActionListener(new ActionListener(){ 
                @Override
                public void actionPerformed(ActionEvent e){
                    setCurrentPanel();
                }
            });
     
            buttonPanel.add(btn1);
            buttonPanel.add(btn2);
            add(buttonPanel, BorderLayout.SOUTH);
     
        } // end method IniTicTacToe()
     
        public void setCurrentPanel()
        {
            cardlayout.show(cardPanel, "2");
            System.out.println("It's working");
     
        } // end method setCurrentPanel()
     
        public static void main(String[] args)
        {   
            CardlayoutTest tictac = new CardlayoutTest();
     
            // moved the next two lines into the constructor
            //        tictac.add(cardPanel);
            //        tictac.setSize(966,600);
            tictac.setVisible(true);
     
        } // end method main()
     
    } // end class TicTacToe

    panel one:
    package cardlayouttest;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import java.awt.event.*;
     
     
     
    public class panel extends JPanel{
        private JButton butt;
        private CardlayoutTest card;
     
     
     
     
        public panel(){
            butt = new JButton("Switch");
            card = new CardlayoutTest();
     
            butt.addActionListener(new ActionListener(){
               @Override
               public void actionPerformed(ActionEvent e){
                   card.setCurrentPanel();
               } 
            });
     
     
     
            add(butt);
     
     
     
     
        }
     
     
     
     
     
        @Override
        public void paint(Graphics g){
            super.paint(g);
            g.setColor(Color.yellow);
            g.fillRect(12, 23, 123, 123);
        }
     
     
     
    }

    Panel two:
    package cardlayouttest;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
     
     
    public class panelTwo extends JPanel{
     
     
     
     
     
     
            @Override
        public void paint(Graphics g){
            super.paint(g);
            g.setColor(Color.RED);
            g.fillRect(12, 23, 123, 123);
        }
     
     
     
    }



    The code "card.setCurrentPanel();" in panel one is what is bothering me. any advice?

    I'm sorry if I'm being annoying, I'm not the best person to describe things.

    And with the cross posting, I was verry desperate, it wont happen again.

  11. #11
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Removing a JPanel from another class

    Quote Originally Posted by kinkita View Post
    And with the cross posting, I was verry desperate, it wont happe again.
    We (among all forums) thank you in advance

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Removing a JPanel from another class

    What you've posted is nonfunctional. As was said on the other forum and in my comments to the code I posted, you can't call the constructor of a second class that calls the constructor of the first class. That creates an infinite loop and will eventually error out into a StackOverflow. Instead, pass an instance of the first class to the second class like this:
        public CardlayoutTest()
        {
            // close the program when the TicTacToe frame is closed and
            // set other characteristics
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            setLocationRelativeTo( null );
            setSize(966,600);
     
            // create the first card, passing an instance of this class
            thePanel = new MyPanel( this );
            thePanel.setOpaque( true );
            thePanel.setBackground( Color.RED );
     
        // . . . etc.
    (Let me know if I need to post this whole class.) I explained this concept in post #7. If you didn't understand, you should have said so that we could go from there.

    Then, you'll have to modify the class you called 'panel', but I changed the name to MyPanel as I've shown below. Class names should begin with capital letters and not be named the same as existing core Java classes.
    package cardlayouttest;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
     
    // this class was called 'panel' in the code you posted 
    public class MyPanel extends JPanel
    {
    //    private JButton butt;
        private CardlayoutTest card;
     
        // the constructor was changed to add the parameter CardlayoutTest card
        // and the JButton butt was removed because it was unnecessary/redundant
        public MyPanel( CardlayoutTest card )
        {
            this.card = card;
     
        } // end constructor MyPanel()
     
        @Override
        public void paint(Graphics g)
        {
            super.paint(g);
            g.setColor(Color.yellow);
            g.fillRect(12, 23, 123, 123);
        }
     
    } // end class MyPanel
    As always, let us know if you have additional questions.

Similar Threads

  1. Adding a Jpanel from another class to JPanel in a main class
    By saniadeyi in forum What's Wrong With My Code?
    Replies: 0
    Last Post: July 22nd, 2013, 03:20 AM
  2. [SOLVED] Pesky <JPanel>.getWidth() and <JPanel>.getHeight() Methods...
    By snowguy13 in forum AWT / Java Swing
    Replies: 1
    Last Post: December 31st, 2011, 03:35 PM
  3. Removing Unnecessary Characters from Servlet class
    By charanraj_d in forum Java Servlet
    Replies: 1
    Last Post: November 2nd, 2011, 10:52 AM
  4. jpanel and using the timer class
    By kswiss in forum AWT / Java Swing
    Replies: 2
    Last Post: March 31st, 2011, 12:35 PM
  5. revalidate() JPanel outside of class it resides
    By Deadbob in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 9th, 2010, 05:14 PM