java - 从驻留在 JFrame 中的 JPanel 中调用 JPanel - 在 netbeans 中

标签 java swing netbeans-8

(已编辑)

我正在创建一个带有动态更改面板的小项目。

我已经能够编写可以使用 JFrame (ManagerScreen) 内按钮的操作事件来调用 JPanel 的代码。例如:

package route66.JFrames;


import route66.pannels.BuyReserve;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import route66.pannels.Buy;
import route66.pannels.BuyReport;
import route66.pannels.CustomerDetails;
import route66.pannels.NewUser;
import route66.pannels.QuotPanel;
import route66.pannels.ReportPanel;
import route66.pannels.Salaries_Com;
import route66.pannels.SaleSucces;

/**
*
* @author Vavu
*/
public class ManagerScreen extends javax.swing.JFrame {

GridBagLayout layout = new GridBagLayout();
Buy BuyPanel = new Buy();
Buy b = new Buy();
BuyReserve buyR = new BuyReserve();
BuyReport brep = new BuyReport();
CustomerDetails cusD = new CustomerDetails();
QuotPanel QP = new QuotPanel();
ReportPanel RP = new ReportPanel();
NewUser NW = new NewUser();
Salaries_Com SalCom = new Salaries_Com();
SaleSucces SalS = new SaleSucces();

boolean visible;

/**
 * Creates new form ManagerScreen
 * @param pabel
 */
public ManagerScreen() {

  initComponents();

  DynamicPanel.setLayout(layout);     
  GridBagConstraints c = new GridBagConstraints();

  c.gridx = 0;
  c.gridy = 0;

  DynamicPanel.add(b,c);
  DynamicPanel.add(buyR,c);
  DynamicPanel.add(brep,c);
  DynamicPanel.add(cusD,c);
  DynamicPanel.add(QP,c);
  DynamicPanel.add(RP,c);
  DynamicPanel.add(NW,c);
  DynamicPanel.add(SalCom,c);
  DynamicPanel.add(SalS,c);


    b.setVisible(false);
    buyR.setVisible(false);
    brep.setVisible(false);
    cusD.setVisible(false);
    QP.setVisible(false);
    RP.setVisible(false);
    NW.setVisible(false);
    SalCom.setVisible(false);
    SalS.setVisible(false);


}



/**
 * 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() {

    DynamicPanel = new javax.swing.JPanel();
    MSbuy = new javax.swing.JButton();
    MSQuotation = new javax.swing.JButton();
    MSReserve = new javax.swing.JButton();
    MSSalCom = new javax.swing.JButton();
    MSReport = new javax.swing.JButton();
    MSCreateNew = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setMinimumSize(new java.awt.Dimension(980, 740));
    getContentPane().setLayout(null);

    DynamicPanel.setBackground(new java.awt.Color(255, 0, 0));
    DynamicPanel.setMaximumSize(new java.awt.Dimension(500, 500));
    DynamicPanel.setMinimumSize(new java.awt.Dimension(500, 500));
    DynamicPanel.setPreferredSize(new java.awt.Dimension(700, 500));

    javax.swing.GroupLayout DynamicPanelLayout = new javax.swing.GroupLayout(DynamicPanel);
    DynamicPanel.setLayout(DynamicPanelLayout);
    DynamicPanelLayout.setHorizontalGroup(
        DynamicPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 700, Short.MAX_VALUE)
    );
    DynamicPanelLayout.setVerticalGroup(
        DynamicPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 500, Short.MAX_VALUE)
    );

    getContentPane().add(DynamicPanel);
    DynamicPanel.setBounds(330, 260, 700, 500);

    MSbuy.setText("Buy");
    MSbuy.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSbuyActionPerformed(evt);
        }
    });
    getContentPane().add(MSbuy);
    MSbuy.setBounds(70, 480, 188, 29);

    MSQuotation.setText("Quotation");
    MSQuotation.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSQuotationActionPerformed(evt);
        }
    });
    getContentPane().add(MSQuotation);
    MSQuotation.setBounds(70, 520, 188, 29);

    MSReserve.setText("Reserve");
    MSReserve.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSReserveActionPerformed(evt);
        }
    });
    getContentPane().add(MSReserve);
    MSReserve.setBounds(70, 440, 188, 29);

    MSSalCom.setText("Salaries & Commission");
    MSSalCom.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSSalComActionPerformed(evt);
        }
    });
    getContentPane().add(MSSalCom);
    MSSalCom.setBounds(70, 400, 188, 29);

    MSReport.setText("Report");
    MSReport.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSReportActionPerformed(evt);
        }
    });
    getContentPane().add(MSReport);
    MSReport.setBounds(70, 560, 187, 29);

    MSCreateNew.setText("Create New User");
    MSCreateNew.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MSCreateNewActionPerformed(evt);
        }
    });
    getContentPane().add(MSCreateNew);
    MSCreateNew.setBounds(70, 600, 187, 29);

    jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    jLabel1.setForeground(new java.awt.Color(0, 0, 204));
    jLabel1.setText("ROUTE66 CAR DEALERSHIP");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(330, 0, 650, 130);

    jLabel3.setText(".");
    getContentPane().add(jLabel3);
    jLabel3.setBounds(0, 0, 330, 260);

    jLabel2.setText(".");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(330, 90, 650, 210);

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

private void MSbuyActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    b.setVisible(false);
    buyR.setVisible(true);
    brep.setVisible(false);
    cusD.setVisible(false);
    QP.setVisible(false);
    RP.setVisible(false);
    NW.setVisible(false);
    SalCom.setVisible(false);
    SalS.setVisible(false);
}                                     

private void MSSalComActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    b.setVisible(false);
    buyR.setVisible(false);
    brep.setVisible(false);
    cusD.setVisible(false);
    QP.setVisible(false);
    RP.setVisible(false);
    NW.setVisible(false);
    SalCom.setVisible(true);
    SalS.setVisible(false);
}                                        

private void MSReserveActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    b.setVisible(false);
    buyR.setVisible(false);
    brep.setVisible(false);
    cusD.setVisible(false);
    QP.setVisible(false);
    RP.setVisible(true);
    NW.setVisible(false);
    SalCom.setVisible(false);
    SalS.setVisible(false);
}                                         

private void MSQuotationActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

private void MSReportActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

private void MSCreateNewActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {  
            new ManagerScreen().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JPanel DynamicPanel;
private javax.swing.JButton MSCreateNew;
private javax.swing.JButton MSQuotation;
private javax.swing.JButton MSReport;
private javax.swing.JButton MSReserve;
private javax.swing.JButton MSSalCom;
private javax.swing.JButton MSbuy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration                   

}

我的问题是 BR 面板 (buyReserve()) 包含两个按钮 - 在 JFrame 内,应该能够从 DynamicPanel() 内调用 buy 面板或 brep 面板 (BuyReport())或者至少我是这么认为的,如果这有道理的话。

所以基本上我已经尝试过以下内容:

 package route66.pannels;

 import java.awt.GridBagConstraints;
 import java.awt.GridBagLayout;
 import route66.pannels.BuyReport;
 import route66.pannels.CustomerDetails;

 /**
 *
 * @author Vavu
 */
 public class BuyReserve extends javax.swing.JPanel {

 GridBagLayout layout = new GridBagLayout();
 Buy BuyPanel = new Buy();
 Buy b = new Buy();
 BuyReserve buyR = new BuyReserve();
 BuyReport brep = new BuyReport();
 CustomerDetails cusD = new CustomerDetails();
 QuotPanel QP = new QuotPanel();
 ReportPanel RP = new ReportPanel();
 NewUser NW = new NewUser();
 Salaries_Com SalCom = new Salaries_Com();
 SaleSucces SalS = new SaleSucces();

/**
 * Creates new form BuyReserve
 */
public BuyReserve() {
    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() {

    btnBuy = new javax.swing.JButton();
    btnReserve = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();

    btnBuy.setText("New Client");
    btnBuy.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnBuyActionPerformed(evt);
        }
    });

    btnReserve.setText("Reserve Client");

    jLabel1.setText("Select Option");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(144, 144, 144)
                    .addComponent(btnBuy)
                    .addGap(35, 35, 35)
                    .addComponent(btnReserve))
                .addGroup(layout.createSequentialGroup()
                    .addGap(230, 230, 230)
                    .addComponent(jLabel1)))
            .addContainerGap(162, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(62, 62, 62)
            .addComponent(jLabel1)
            .addGap(72, 72, 72)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnBuy)
                .addComponent(btnReserve))
            .addContainerGap(201, Short.MAX_VALUE))
    );
}// </editor-fold>                        

private void btnBuyActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:

    b.setVisible(true);   
}                                      


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

}

如果我运行包含第二个代码片段的 ManagerScreen,则会收到错误。我还尝试过其他类型的代码,最终会显示 jpanel 没有主类等信息。

所以,希望在这个阶段我已经能够表达我的观点,以便能够(再次)提出问题;如何在 JFrame 内的面板中调用面板?

最佳答案

您声明您想“调用”JPanel,但这实际上没有任何意义。如果您的目标是交换 JPanel View ,那么最简单的方法就是使用 CardLayout。有关此有用工具的更多信息,请参阅CardLayout Tutorial

例如:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class ManagerPanel extends JPanel {
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardLayoutPanel = new JPanel(cardLayout);
    private BuyPanel buyPanel = new BuyPanel(this);
    private BuyReportPanel buyReportPanel = new BuyReportPanel(this);
    private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<String> panelComboBox = new JComboBox<>(comboModel);

    public ManagerPanel() {
        comboModel.addElement(BuyPanel.BUY);
        comboModel.addElement(BuyReportPanel.BUY_REPORT);
        panelComboBox.addActionListener(evt -> {
            String key = panelComboBox.getSelectedItem().toString();
            cardLayout.show(cardLayoutPanel, key);
        });
        JPanel comboPanel = new JPanel();
        comboPanel.add(panelComboBox);

        cardLayoutPanel.add(buyPanel, BuyPanel.BUY);
        cardLayoutPanel.add(buyReportPanel, BuyReportPanel.BUY_REPORT);

        setLayout(new BorderLayout());
        add(cardLayoutPanel, BorderLayout.CENTER);
        add(comboPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        ManagerPanel mainPanel = new ManagerPanel();

        JFrame frame = new JFrame("ManagerPanel");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    public void nextPanel() {
        cardLayout.next(cardLayoutPanel);
    }
}

class BuyReportPanel extends JPanel {
    public final static String BUY_REPORT = "Buy Report";
    private ManagerPanel managerPanel;

    public BuyReportPanel(ManagerPanel managerPanel) {
        this.managerPanel = managerPanel;
        add(new JLabel(BUY_REPORT), SwingConstants.CENTER);
        add(new JButton(new NextPanelAction(managerPanel)));
    }
}

class BuyPanel extends JPanel {
    public final static String BUY = "Buy";
    private ManagerPanel managerPanel;

    public BuyPanel(ManagerPanel managerPanel) {
        setPreferredSize(new Dimension(400, 300));
        this.managerPanel = managerPanel;
        add(new JLabel(BUY), SwingConstants.CENTER);
        add(new JButton(new NextPanelAction(managerPanel)));
    }
}

class NextPanelAction extends AbstractAction {
    private ManagerPanel managerPanel;

    public NextPanelAction(ManagerPanel managerPanel) {
        super("Next Panel");
        this.managerPanel = managerPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        managerPanel.nextPanel();
    }
}

请注意,我已将主类(此处为 ManagerPanel)传递给其他类,因此它们可以根据需要调用其任何公共(public)方法,包括 nextPanel()

关于java - 从驻留在 JFrame 中的 JPanel 中调用 JPanel - 在 netbeans 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312503/

相关文章:

Java 8 : extract a substream from a stream

java - 停止 Tomcat 应用程序中的线程 - 哪种方法?

java - JTree 线型和 Nimbus

java - 向 JTable 添加行

java - Netbeans找不到JDK和JRE

css - 为什么 netbeans 不运行我的 CSS 文件?

java - 使用 Java NetBeans 制作我自己的 GUI 构建器

java - 单选按钮状态始终为 'checked'

java - 在窗口应用程序中将图像添加到内容 Pane

java - 尝试从 netbeans IDE 8.2 连接到 MySQL 服务器时出错