Java NetBeans 中 JFrame 中的 JPanel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/495217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:21:18  来源:igfitidea点击:

JPanel in JFrame in NetBeans

javaswingnetbeansjframejpanel

提问by

I have created a Java application (project) in NetBeans, in which I have designed a JFramewith menu bar, and different JPanels. I want these JPanelsto appear inside the JFrameon action of different menu items, so that whenever the menu items are clicked different JPanelsshould appear inside the JFrame. I have designed both JFrame& JPanelseparately, but I couldn't link them together.

我在 NetBeans 中创建了一个 Java 应用程序(项目),在其中我设计了一个JFrame带菜单栏的和不同的JPanels. 我希望这些JPanels出现在JFrame不同菜单项的on 操作中,以便每当单击菜单项时,不同的菜单项JPanels都应出现在JFrame. 我设计了两个JFrameJPanel分开,但我无法将它们链接在一起。

Please help me out friends.

请朋友帮帮我。

回答by Yngve Sneen Lindal

You could use Card Layout for this. A Card Layout can contain many components (JPanel in your case), and you can switch between them. It's easy to add a card layout in the netbeans palette.

您可以为此使用卡片布局。卡片布局可以包含许多组件(在您的情况下为 JPanel),您可以在它们之间切换。在 netbeans 调色板中添加卡片布局很容易。

Doc:

文件:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/CardLayout.html

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/CardLayout.html

回答by Kyle G

If you want the menus to react to clicks, you need to add Listeners to the menu items, Which in response will show the correct panel.

如果您希望菜单对点击做出反应,您需要向菜单项添加监听器,作为响应,它将显示正确的面板。

回答by Outlaw Programmer

The Matisse GUI builder has pretty good support for the "JTabbedPane" control, if that's what you're looking for. You can drag the TabbedPane container into your forms, then drag other containers onto it to create new tabs.

Matisse GUI builder 对“JTabbedPane”控件有很好的支持,如果这就是你要找的。您可以将 TabbedPane 容器拖到表单中,然后将其他容器拖到它上面以创建新选项卡。

If you're looking for more advanced behavior, such as hiding/showing different containers when the user presses different buttons, you will need to write some code; the GUI builder isn't equipped to handle this.

如果您正在寻找更高级的行为,例如当用户按下不同的按钮时隐藏/显示不同的容器,您将需要编写一些代码;GUI 构建器没有能力处理这个问题。

回答by Outlaw Programmer

after changing the panel in JFrame do the frameObj.pack();

在 JFrame 中更改面板后执行 frameObj.pack();

回答by Russ Hayward

It appears from one of your comments that you wish to dynamically create the JPanels when the buttons are clicked. If this is the case then CardLayout is not ideal. It is relatively easy to achieve the same effect yourself. The code will look something like this:

从您的评论之一看来,您希望在单击按钮时动态创建 JPanel。如果是这种情况,则 CardLayout 并不理想。自己实现同样的效果是比较容易的。代码如下所示:

public void actionPerformed(ActionEvent event) {
    Container contentPane = frame.getContentPane();
    contentPane.removeAll();
    contentPane.add(new YourPanel());
    contentPane.invalidate();
    contentPane.repaint();
}

That assumes that the changing panel is the only component in the frame. If it is not then add a JPanel with a BorderLayout to the content pane in Matisse and then add the new panels to that rather than the content pane.

这假设更改面板是框架中的唯一组件。如果不是,则将带有 BorderLayout 的 JPanel 添加到 Matisse 的内容窗格,然后将新面板添加到该面板而不是内容窗格。

回答by shohan

First you save it as a .javafile. This is the main jframe class. You run it first. Then you see the external panel add to it by constructor.

首先将其保存为.java文件。这是主要的 jframe 类。你先运行它。然后您会看到外部面板通过构造函数添加到它。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on Apr 20, 2010, 5:20:26 PM
 */

package game;

import javax.swing.SwingUtilities;

/**
 *
 * @author S.M. Mahmudul hasan
 */
public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        addPanel();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        firstPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout firstPanelLayout = new javax.swing.GroupLayout(firstPanel);
        firstPanel.setLayout(firstPanelLayout);
        firstPanelLayout.setHorizontalGroup(
            firstPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 457, Short.MAX_VALUE)
        );
        firstPanelLayout.setVerticalGroup(
            firstPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(firstPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(firstPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    private void addPanel() {
        MainPanel m=new MainPanel();
        this.getContentPane().remove(0);
        firstPanel.removeAll();
        javax.swing.GroupLayout firstPanelLayout = new javax.swing.GroupLayout(firstPanel);
        firstPanel.setLayout(firstPanelLayout);
        firstPanelLayout.setHorizontalGroup(
            firstPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(firstPanelLayout.createSequentialGroup()
                .addGap(78, 78, 78)
                .addComponent(m, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(79, Short.MAX_VALUE))

        );
        firstPanelLayout.setVerticalGroup(
            firstPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(firstPanelLayout.createSequentialGroup()
                .addGap(25, 25, 25)

                .addComponent(m, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(23, 23, 23))
        );
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(firstPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(firstPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        SwingUtilities.updateComponentTreeUI(this.getContentPane());
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel firstPanel;
    // End of variables declaration

}

Panel class:

面板类:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainPanel.java
 *
 * Created on Apr 20, 2010, 5:21:03 PM
 */

package game;

import java.awt.Graphics;

/**
 *
 * @author S.M. Mahmudul hasan
 */
public class MainPanel extends javax.swing.JPanel {

    /** Creates new form MainPanel */
    public MainPanel() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder("paintable area"));

        jLabel1.setText("Paintable area");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(86, 86, 86)
                .addComponent(jLabel1)
                .addContainerGap(128, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(103, 103, 103)
                .addComponent(jLabel1)
                .addContainerGap(119, Short.MAX_VALUE))
        );
    }// </editor-fold>

  @Override public void paintComponent(Graphics g) {
         super.paintComponent(g);    // paints background
         g.drawString("shohan", 50, 100);
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    // End of variables declaration

}

回答by Rajshri

If You really want make your GUI more attractive then use JDesktopPaneand see the result.

如果您真的想让您的 GUI 更具吸引力,请使用JDesktopPane并查看结果。