简体   繁体   English

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

[英]Calling a JPanel from within a JPanel that resides in a JFrame - in netbeans

(Edited) (已编辑)

I'm creating a small project with dynamically changing panels. 我正在创建一个动态更改面板的小项目。

I've been able to write code that can call a JPanel using an action event from a button within the the JFrame (ManagerScreen). 我已经能够编写代码,使用JFrame(ManagerScreen)中的按钮上的操作事件来调用JPanel。 For example: 例如:

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                   

} }

My problem is that the BR panel (buyReserve()), containing two buttons - within the JFrame, is supposed to be able to call either the buy panel or brep panel (BuyReport()) from the within the DynamicPanel() or at least thats what I think, if that makes sense. 我的问题是,BR面板(buyReserve())包含两个按钮-在JFrame中,应该能够从DynamicPanel()内或至少从内部调用购买面板或brep面板(BuyReport())。那就是我的想法,如果那是有道理的。

so basically I've tried somethings including the following: 所以基本上我已经尝试了以下方法:

 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                   

} }

If I run the ManagerScreen with the inclusion of the second code snippet I get an error. 如果运行包含第二个代码段的ManagerScreen,则会收到错误消息。 I've also tried other types of code that end up saying things like the jpanel doesn't have a main class n so on. 我还尝试了其他类型的代码,最终导致诸如jpanel的类没有主类n之类的东西。

So, hopefully by this stage I've been able to get my point across to be to able ask (again); 因此,希望到这个阶段,我已经能够阐明我的观点了(能够再次提出); how do I call a panel, within a panel that is inside a JFrame? 如何在JFrame内的面板内调用面板?

You state that you want to "call" JPanels, but this doesn't really have any meaning. 您声明要“调用” JPanel,但这实际上没有任何意义。 If your goal is to swap JPanel views, then the simplest and easiest way is to use a CardLayout. 如果您的目标是交换 JPanel视图,那么最简单,最简单的方法就是使用CardLayout。 For more on this useful tool, please see the CardLayout Tutorial . 有关此有用工具的更多信息,请参见CardLayout Tutorial

For example: 例如:

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();
    }
}

Note that I've passed my main class, here ManagerPanel, into other classes, and so they can call any of its public methods including nextPanel() , as needed. 请注意,我已经将我的主类(这里为ManagerPanel)传递给其他类,因此它们可以根据需要调用其任何公共方法,包括nextPanel()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM