将一个JPanel从另一个Java类放到另一个JPanel上

时间:2015-11-11 08:17:13

标签: java swing jpanel

我正在开发Java Swing应用程序。我的应用程序有两个Java类。在class1.java内,我包括JFrame,JButton和JPanel(panel1)。当我单击按钮时我想隐藏panel1,并且应该显示class2.java的panel2。我在class1.java的按钮actionPerformed方法中尝试了这个方法。但它没有用。

class2 pnl = new class2();     
this.remove(panel1);
this.add(pnl); 
this.validate();
this.repaint();

2 个答案:

答案 0 :(得分:0)

分析

您只是希望JComponents上显示JFrame。我们可以使用单个JPanel来实现此目的,但在JComponents的动作侦听器中添加JButton并将其移除。

在不查看实际代码的情况下,最好采用可管理的方式来访问代码和实例化对象。下面列出的代码创建了一种很好且易于管理的方法。

实现此

下面列出了整个课程,并附有解释说明。

package swing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

    public class MultiPaneledFrame {

        JFrame frame = new JFrame();
        JPanel window = new JPanel();

        // As you can see, we create an array containing all your JComponents.
        // We have two of these, to simulate multiple JPanel's.
        List<JComponent> window1Contents = new ArrayList<JComponent>();
        List<JComponent> window2Contents = new ArrayList<JComponent>();
        // NOTE: The above Lists can instead be stuck in their own class like asked for,
        // and instantiated on Class invocation.

        JButton goto2 = new JButton("Goto Panel 2");
        JButton goto1 = new JButton("Goto Panel 1");

        int panelToShow = 0; // 0 - First "panel".
                               // 1 - Second "panel".

        // Main method of class. Change 'Multi_Paneled_Frame' to the name of your Class.
        public MultiPaneledFrame() {
            // Execute anything else you want here, before we start the frame.
            window1Contents.add(goto2);
            window2Contents.add(goto1);

            // Here is where I personally am setting the coordinates of the JButton's on the JPanel.
            goto2.setPreferredSize(new Dimension(200, 100));
            goto1.setPreferredSize(new Dimension(200, 100));
            //goto2.setBounds(5, 5, 150, 30); < Used for 'null' layout.
            //goto1.setBounds(5, 5, 150, 30); < Used for 'null' layout.

            goto2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    addComponents(panelToShow = 1);
                }
            });
            goto1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    addComponents(panelToShow = 0);
                }
            });

            initialiseFrame();
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new MultiPaneledFrame();
                }
            });
        }

        private void initialiseFrame() {
            frame.setSize(600, 400); // Change it accordingly.
            // Optional
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setResizable(false);
            // Needed
            frame.setVisible(true);
            frame.add(window);
            window.setLayout(new BorderLayout()); // Assuming your using a BorderLayout.
            //window.setLayout(null); < Uses 'null' layout.
            addComponents(panelToShow);

            // I always like to make sure that everything is on the frame nicely.
            frame.repaint();
            frame.validate();
        }

        private void addComponents(int panelNo) {
            if (panelNo == 0) {
                for (JComponent component : window1Contents) {
                    window.removeAll(); // We're removing everything that it contains and replacing it...
                    window.revalidate();
                    window.add(component, BorderLayout.CENTER);
                    //window.add(component); < Uses 'null' layout.
                    // Since we are using the first panel, we are adding
                    // everything from the first list of components to the window...
                }
            } else {
                for (JComponent component : window2Contents) {
                    window.removeAll(); // We're removing everything that it contains and replacing it...
                    window.revalidate();
                    window.add(component, BorderLayout.CENTER);
                    //window.add(component); < Uses 'null' layout.
                    // Since we are using the second panel, we are adding
                    // everything from the second list of components to the window...
                }
            }

            // Refreshes the frame.
            frame.repaint();
            frame.validate();
        }
    }

结论

虽然有无数种方法可以实现这样的目标,但我所采用的方式是半效率的,而且非常灵活。如果您有任何疑虑,请随时编辑代码或提出问题,我将很乐意回复。

PS:此代码经过测试,适用于运行OS X 10.11和Java Version 8 Update 65的Macbook Air。

答案 1 :(得分:-1)

CardLayout应该是您的解决方案。在本教程中,他们将通过在ComboBox中选择一个值来展示如何从面板切换到另一个面板。

对CarLayout的一点解释:

CardLayout允许您将不同的面板放在彼此的顶部,但当时只显示一个。使用您的代码,您可以选择要显示的代码。

<强>初始化:

this.setLayout(new CardLayout());

class1 pnl1 = new class1();
class2 pnl2 = new class2();

this.add(pnl1, "PANEL1");
this.add(pnl2, "PANEL2");

关于你的按钮actionPerformed:

CardLayout cl = (CardLayout)(this.getLayout());
cl.show(this, "PANEL2");