有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从单独的JForm访问JComboBox数据

我花了一点时间浏览Stack Overflow和internet来寻找我问题的答案,但我发现所有答案都很难理解,而且我很不确定是否有任何答案与我的问题有关,因此我决定在正确的上下文中需要帮助

我正在创建一个程序,它将根据输入的特定类型的图形给出一系列解决方案。我真诚地努力在第一个JFrame中从我的JComboBox中获取数据,并在第二个JFrame中显示它

我有两个类,graphquationsolvergui和DefineEquation。我正在使用Netbeans IDE,GraphquationSolverGUI是我的“项目”

图形方程SolverGUI:

private void graphSelectionActionPerformed(java.awt.event.ActionEvent evt) {                                               
    String graphSelectionGUI = (String)graphSelection.getSelectedItem();
    //graphSelectedTextField.setText(graphSelectionGUI);
    DefineEquation graphSelectedObj = new DefineEquation(graphSelectionGUI);
    graphSelectedObj.addItem(graphSelectionGUI);

这是JComboBox,我希望选择将数据发送到另一个类。JComboBox称为graphSelection。您会注意到注释文本是我将JTextField设置为JComboBox的值,这是这个JForm的内部,我自己使用它来测试以确保数据输入正确,它可以工作,并且我可以在这个JFrame中显示数据。下面的另一个代码是我试图创建一个对象并通过它传递数据,我对对象有点生疏,因为我已经有一段时间没有使用它们了,如果我让你哭了,很抱歉

定义方程式:

public DefineEquation(String graphSelected) {
    this.graphSelected = graphSelected;
} //If anyone cares here is my constructor for the object

public void addItem(String graphSelectedString1){
    DefineEquation graphSelectedObj = new DefineEquation(graphSelected);
    String graphSelectedStringMAIN = graphSelectedString1.toString();
    selectedGraph.setText(graphSelectedStringMAIN);
}

上面是我创建的将数据添加到名为selectedGraph的JTextField的方法。您会注意到我有graphSelectedString1和graphSelectedStringMAIN,其中我将字符串转换为明显冗余的字符串。我这样做只是为了以防万一,这是多余的,很抱歉让你畏缩

我知道这可能很难理解,你可能会发现很难理解我的要求。简单地说,我如何将数据从一个JFrame JComboBox传递到另一个JFrame中的JTextField?我会使用对象吗?如果可以的话,请试着带我看一下,我很困惑。如果您希望通读所有内容,我将在下面粘贴我的所有代码

图形方程SolverGUI:

/*
* To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author MatthewAlanTroutman
 */

public class GraphEquationSolverGUI extends javax.swing.JFrame {

/**
 * Creates new form GraphEquationSolverGUI
 */

public GraphEquationSolverGUI() {
    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() {

    jSpinner1 = new javax.swing.JSpinner();
    welcome = new javax.swing.JLabel();
    programDescription = new javax.swing.JLabel();
    graphsOffered = new javax.swing.JLabel();
    linear = new javax.swing.JLabel();
    bilinear = new javax.swing.JLabel();
    quadratic = new javax.swing.JLabel();
    cubic = new javax.swing.JLabel();
    exponential = new javax.swing.JLabel();
    graphSelectionText = new javax.swing.JLabel();
    graphSelection = new javax.swing.JComboBox();
    help = new javax.swing.JButton();
    close = new javax.swing.JButton();
    next = new javax.swing.JButton();
    graphSelectedTextField = new javax.swing.JTextField();
    graphSelectedLabel = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("GraphEquationSolver");
    setBackground(new java.awt.Color(255, 255, 255));

    welcome.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    welcome.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    welcome.setText("Welcome");
    welcome.setPreferredSize(new java.awt.Dimension(800, 100));

    programDescription.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    programDescription.setText("You can use this program to find a variety of solutions for different types of graphs, please select a graph to begin");
    programDescription.setPreferredSize(new java.awt.Dimension(800, 75));

    graphsOffered.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
    graphsOffered.setText("Graphs we offer:");

    linear.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    linear.setText("- Linear");

    bilinear.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    bilinear.setText("- Bilinear");

    quadratic.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    quadratic.setText("- Quadratic");

    cubic.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    cubic.setText("- Cubic");

    exponential.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
    exponential.setText("- Exponential");

    graphSelectionText.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
    graphSelectionText.setText("Please select your graph");

    graphSelection.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Linear", "Bilinear", "Quadratic", "Cubic", "Exponential" }));
    graphSelection.setToolTipText("");
    graphSelection.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            graphSelectionActionPerformed(evt);
        }
    });

    help.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    help.setText("Help");

    close.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    close.setText("Close");
    close.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            closeActionPerformed(evt);
        }
    });

    next.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
    next.setText("Next");
    next.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            nextActionPerformed(evt);
        }
    });

    graphSelectedTextField.setEditable(false);

    graphSelectedLabel.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
    graphSelectedLabel.setText("Graph Selected");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(240, 240, 240))
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(240, 240, 240)
                    .addComponent(programDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(184, 184, 184)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(exponential)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(graphsOffered)
                                .addComponent(linear)
                                .addComponent(bilinear)
                                .addComponent(quadratic)
                                .addComponent(cubic))
                            .addGap(311, 311, 311)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(graphSelectionText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(graphSelection, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(graphSelectedTextField)
                                .addComponent(graphSelectedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                .addGroup(layout.createSequentialGroup()
                    .addGap(231, 231, 231)
                    .addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(240, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(34, 34, 34)
            .addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(programDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(73, 73, 73)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(graphsOffered)
                .addComponent(graphSelectionText))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(graphSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(linear)
                .addComponent(graphSelectedLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(bilinear)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(quadratic))
                .addComponent(graphSelectedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(cubic)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(exponential)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 219, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(169, 169, 169))))
    );

    graphSelection.getAccessibleContext().setAccessibleName("");
    help.getAccessibleContext().setAccessibleName("help");
    close.getAccessibleContext().setAccessibleName("close");

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

private void graphSelectionActionPerformed(java.awt.event.ActionEvent evt) {                                               
    String graphSelectionGUI = (String)graphSelection.getSelectedItem();
    graphSelectedTextField.setText(graphSelectionGUI);
    //DefineEquation graphSelectedObj = new DefineEquation(graphSelectionGUI);
    //graphSelectedObj.addItem(graphSelectionGUI);

}                                              

private void closeActionPerformed(java.awt.event.ActionEvent evt) {                                      
    System.exit(0);
}                                     

private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                     
    this.setVisible(false);
    new DefineEquation().setVisible(true);
}                                    

/**
 * @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(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GraphEquationSolverGUI.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 GraphEquationSolverGUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel bilinear;
private javax.swing.JButton close;
private javax.swing.JLabel cubic;
private javax.swing.JLabel exponential;
private javax.swing.JLabel graphSelectedLabel;
private javax.swing.JTextField graphSelectedTextField;
private javax.swing.JComboBox graphSelection;
private javax.swing.JLabel graphSelectionText;
private javax.swing.JLabel graphsOffered;
private javax.swing.JButton help;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JLabel linear;
private javax.swing.JButton next;
private javax.swing.JLabel programDescription;
private javax.swing.JLabel quadratic;
private javax.swing.JLabel welcome;
// End of variables declaration                   
}

定义方程式:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author MatthewAlanTroutman
 */
public class DefineEquation extends javax.swing.JFrame {
//public class DefineEquation extends GraphEquationSolverGUI {
public String graphSelected;

/**
 * Creates new form DefineEquation
 */
public DefineEquation() {
    initComponents();
}
public DefineEquation(String graphSelected) {
    this.graphSelected = graphSelected;
}



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

    selectedGraph = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    selectedGraph.setEditable(false);
    selectedGraph.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            selectedGraphActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(435, 435, 435)
            .addComponent(selectedGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(596, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(126, 126, 126)
            .addComponent(selectedGraph, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(646, Short.MAX_VALUE))
    );

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

private void selectedGraphActionPerformed(java.awt.event.ActionEvent evt) {                                              

}                                             
public void addItem(String graphSelectedString1){
    DefineEquation graphSelectedObj = new DefineEquation(graphSelected);
    String graphSelectedStringMAIN = graphSelectedString1.toString();
    selectedGraph.setText(graphSelectedStringMAIN);
}

/**
 * @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(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(DefineEquation.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 DefineEquation().setVisible(true);
        }

    });
}

// Variables declaration - do not modify                     
private javax.swing.JTextField selectedGraph;
// End of variables declaration                   
}

您会注意到我试图“扩展”我的第一个JFrame,但这导致了第二个JFrame“窗口”以某种方式与第一个JFrame“窗口”相结合

概念图像:

enter image description here

编辑1:这是最好的解决方法吗?如果是这样,我将如何移动数据?对象目前让我困惑,还有一些非静态和静态的问题,这些问题似乎是无效的,因为我没有任何静态的东西。如果这不是最好的方法,我该怎么办?我要睡觉了,请你给我建议和帮助,我不仅感到绝望,而且感到失落

编辑2:我正在尝试使用切基拉先生的答案,在回答之前参考他的答案,因为这可能会有所帮助

编辑3:仍然停留在需要详细帮助的谈话中,很抱歉要求这么高,但我不能完全理解这一点

编辑4:我想我已经找到了一个重大突破。我已经想出了如何解决这个问题,但我真的认为我需要理解这一点。无论如何,我有一个新类和一个不同类的新文本字段。我仍然有这个问题,我不能显示textfield的值,但出于某种原因,我可以输出相同的值。我想这更容易展示

这就是类选择解决方案:

public void displayText(String textToSet) {
    displayQuadraticEquation.setText(textToSet);
    System.out.println(textToSet);
}

这就是定义的二次方程:

private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                     
    this.setVisible(false);
    new SelectSolutionsQuadratic().setVisible(true);
    SelectSolutionsQuadratic transferMe = new SelectSolutionsQuadratic();
    transferData = aQuadraticSpinner.getValue().toString() + " " + addSubQuadraticComboBox.getSelectedItem(); 
    transferMe.displayText(transferData);
}                     

所以基本上我很困惑为什么我可以把一个值从defineequationsquared发送到selectsolutionsquared,然后用系统输出。出来println();但是将文本字段设置为该值


共 (3) 个答案

  1. # 1 楼答案

    我的建议是创建两个JPanel类,一个保存JComboBox,另一个显示或需要结果。假设您已经这样做并调用了第一个类HoldsComboBoxPanel,第二个类名为ShowSelectionPanel,那么您将为HoldsComboxPanel提供两个方法,一个用于获取当前选择,一个是“getter”方法,另一个是允许外部类向combobox添加ActionListener。例如,简而言之:

    public class HoldsComboBoxPanel extends JPanel {
       public static final String NAME = "holds combobox panel";
       // sample data
       private static final String[] DATA = { "Monday", "Tuesday", "Wednesday",
             "Thursday", "Friday" };
       private JComboBox<String> comboBox = new JComboBox<>(DATA);
    
       public HoldsComboBoxPanel() {
           // add the comboBox into our class here
       }
    
       // method to add a listener
       public void addComboBoxListener(ActionListener listener) {
          comboBox.addActionListener(listener);
       }
    
       // getter method
       public String getComboSelection() {
          return (String) comboBox.getSelectedItem();
       }
    
    }
    

    您的第二个类,需要数据的类,将有一个setter方法,允许外部类将组合选择推入其中。假设它有一个名为displayField的JTextField来显示选择,它的代码可能如下所示:

    public class ShowSelectionPanel extends JPanel {
       public static final String NAME = "show selection panel";
       private JTextField displayField = new JTextField(10);
    
       public ShowSelectionPanel() {
          // add the displayField to the JPanel here
       }
    
       // setter method
       public void setDisplayText(String text) {
          displayField.setText(text);
          // or do whatever else you want to do with the selection
       }
    }
    

    然后你会有另一个使用CardLayout的类,它允许在上面的视图JPanel之间进行交换,比如MainPanel。它可以使用CardLayout来允许您交换JPanel,有一个公共方法来允许外部类交换“card”JPanel,它可以同时保存一个HoldsComboxPanel字段和一个ShowSelectionPanel字段,并可以通过将ActionListener添加到combobox来链接它们,如下所示:

    public class MainPanel extends JPanel {
       private CardLayout cardLayout = new CardLayout();
       private MenuPanel menuPanel = new MenuPanel();
       private HoldsComboBoxPanel holdsComboBoxPanel = new HoldsComboBoxPanel();
       private ShowSelectionPanel showSelectionPanel = new ShowSelectionPanel();
    
       public MainPanel() {
          // add an ActionListener to the JComboBox
          holdsComboBoxPanel.addComboBoxListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                // get the combo's selected String
                String selection = holdsComboBoxPanel.getComboSelection();
                if (selection != null) {
                   // push it into showSelection
                   showSelectionPanel.setDisplayText(selection);
                }
             }
          });
    
          setLayout(cardLayout);
          add(menuPanel, MenuPanel.NAME);
          add(holdsComboBoxPanel, HoldsComboBoxPanel.NAME);
          add(showSelectionPanel, ShowSelectionPanel.NAME);
       }
    
       // method that allows outside classes to swap views
       public void showCard(String key) {
          cardLayout.show(this, key);
       }
    }
    

    整个过程加上一些额外的代码,允许在“卡片”中移动,可能看起来像这样:

    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class SimpleMultPanels {
       private static void createAndShowGui() {
          // create JFrame
          JFrame frame = new JFrame("SimpleMultPanels");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
          // add our MainPanel to the JFrame
          frame.getContentPane().add(new MainPanel());
          frame.pack(); // pack it
          frame.setLocationByPlatform(true);
          frame.setVisible(true); // show it
       }
    
       public static void main(String[] args) {
          // this is for starting our Swing app on the event thread
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class MainPanel extends JPanel {
       private CardLayout cardLayout = new CardLayout();
    
       // the three "card" JPanels that this JPanel displays:
       private MenuPanel menuPanel = new MenuPanel();
       private HoldsComboBoxPanel holdsComboBoxPanel = new HoldsComboBoxPanel();
       private ShowSelectionPanel showSelectionPanel = new ShowSelectionPanel();
    
       // Actions for our JButtons
       private ExitAction exitAction = new ExitAction();
       private ShowAction backToMenuAction = new ShowAction(this, "Back to Menu",
             MenuPanel.NAME, KeyEvent.VK_B);
       private ShowAction toHoldsComboAction = new ShowAction(this, "Combo Panel",
             HoldsComboBoxPanel.NAME, KeyEvent.VK_C);
       private ShowAction toShowSelectionAction = new ShowAction(this,
             "Show Selection", ShowSelectionPanel.NAME, KeyEvent.VK_S);
    
       public MainPanel() {
          // add an ActionListener to the JComboBox
          holdsComboBoxPanel.addComboBoxListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                // get the combo's selected String
                String selection = holdsComboBoxPanel.getComboSelection();
                if (selection != null) {
                   // push it into showSelection
                   showSelectionPanel.setDisplayText(selection);
                }
             }
          });
    
          // add Actions to class to allow swapping of cards and
          holdsComboBoxPanel.addButtonAction(backToMenuAction);
          holdsComboBoxPanel.addButtonAction(toShowSelectionAction);
          holdsComboBoxPanel.addButtonAction(exitAction); // and to exit gui
    
          showSelectionPanel.addButtonAction(backToMenuAction);
          showSelectionPanel.addButtonAction(toHoldsComboAction);
          showSelectionPanel.addButtonAction(exitAction);
    
          menuPanel.addButtonAction(toHoldsComboAction);
          menuPanel.addButtonAction(toShowSelectionAction);
          menuPanel.addButtonAction(exitAction);
    
          setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    
          // set our layout
          setLayout(cardLayout);
    
          // and add our "card" JPanels
          add(menuPanel, MenuPanel.NAME);
          add(holdsComboBoxPanel, HoldsComboBoxPanel.NAME);
          add(showSelectionPanel, ShowSelectionPanel.NAME);
       }
    
       // method that allows outside classes to swap views
       public void showCard(String key) {
          cardLayout.show(this, key);
       }
    }
    
    @SuppressWarnings("serial")
    class HoldsComboBoxPanel extends JPanel {
       // constant String that will be used by the CardLayout
       public static final String NAME = "holds combobox panel";
    
       // sample data
       private static final String[] DATA = { "Monday", "Tuesday", "Wednesday",
             "Thursday", "Friday" };
       private JComboBox<String> comboBox = new JComboBox<>(DATA);
    
       // JPanel to hold buttons to allow moving between cards
       private JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
    
       public HoldsComboBoxPanel() {
          comboBox.setSelectedIndex(-1);
          JPanel centerPanel = new JPanel();
          centerPanel.add(comboBox);
    
          setLayout(new BorderLayout());
          add(centerPanel, BorderLayout.CENTER);
          add(buttonPanel, BorderLayout.SOUTH);
       }
    
       // method to add a listener
       public void addComboBoxListener(ActionListener listener) {
          comboBox.addActionListener(listener);
       }
    
       // getter method
       public String getComboSelection() {
          return (String) comboBox.getSelectedItem();
       }
    
       // create a new JButton with an Action and add to buttonPanel
       public void addButtonAction(Action action) {
          buttonPanel.add(new JButton(action));
       }
    }
    
    @SuppressWarnings("serial")
    class ShowSelectionPanel extends JPanel {
       public static final String NAME = "show selection panel";
       private static final int PREF_W = 300;
       private static final int PREF_H = PREF_W;
       private JTextField displayField = new JTextField(10);
       private JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
    
       public ShowSelectionPanel() {
          displayField.setFocusable(false);
    
          JPanel centerPanel = new JPanel();
          centerPanel.add(displayField);
    
          setLayout(new BorderLayout());
          add(centerPanel, BorderLayout.CENTER);
          add(buttonPanel, BorderLayout.SOUTH);
       }
    
       // code to make our GUI a little larger
       @Override
       public Dimension getPreferredSize() {
          Dimension superSz = super.getPreferredSize();
          if (isPreferredSizeSet()) {
             return superSz;
          }
          int prefW = Math.max(superSz.width, PREF_W);
          int prefH = Math.max(superSz.height, PREF_H);
          return new Dimension(prefW, prefH);
       }
    
       // setter method
       public void setDisplayText(String text) {
          displayField.setText(text);
          // or do whatever else you want to do with the selection
       }
    
       public void addButtonAction(Action action) {
          buttonPanel.add(new JButton(action));
       }
    
    }
    
    @SuppressWarnings("serial")
    class MenuPanel extends JPanel {
       public static final String NAME = "menu panel";
       private JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 0, 5));
    
       public MenuPanel() {
          setLayout(new GridBagLayout());
          add(buttonPanel);
       }
    
       public void addButtonAction(Action action) {
          buttonPanel.add(new JButton(action));
       }
    }
    
    @SuppressWarnings("serial")
    class ShowAction extends AbstractAction {
       private MainPanel mainPanel;
       private String key;
    
       /**
        * Abstract Action used by JButtons
        * @param mainPanel: the JPanel that uses the CardLayout
        * @param name: The name displayed by the button
        * @param key: The key used in the CardLayout#show(String key) mehtod
        * @param mnemonic: the JButton's mnemonic char
        */
       public ShowAction(MainPanel mainPanel, String name, String key, int mnemonic) {
          super(name);
          putValue(MNEMONIC_KEY, mnemonic);
          this.mainPanel = mainPanel;
          this.key = key;
       }
    
       @Override
       public void actionPerformed(ActionEvent e) {
          // tell the mainPanel to show the card associated with the key
          mainPanel.showCard(key);
       }
    }
    
    // class of mine to allow disposing of a window
    // It's a little complex to allow it to work with either a JButton
    // or a JMenuItem
    @SuppressWarnings("serial")
    class ExitAction extends AbstractAction {
       public ExitAction() {
          super("Exit");
          putValue(MNEMONIC_KEY, KeyEvent.VK_X);
       }
    
       @Override
       public void actionPerformed(ActionEvent e) {
          // get the button that caused this action
          Object source = e.getSource();
          if (source instanceof AbstractButton) {
             AbstractButton exitButton = (AbstractButton) source;
    
             // get the parent top level window
             Window topWindow = SwingUtilities.getWindowAncestor(exitButton);
             if (topWindow == null) { // if null, then likely in a JMenuItem
                // so we have to get its jpopupmenu parent
                Container parent = exitButton.getParent();
                if (parent instanceof JPopupMenu) {
                   JPopupMenu popupMenu = (JPopupMenu) parent;
    
                   // get the invoker for the pop up menu
                   Component invoker = popupMenu.getInvoker();
                   if (invoker != null) {
                      // and get *its* top level window
                      topWindow = SwingUtilities.getWindowAncestor(invoker);
                   }
                }
             }
             if (topWindow != null) {
                // dispose of the top-level window
                topWindow.dispose();
             }
          }
       }
    }
    
  2. # 2 楼答案

    所以我真的很笨,创建了两个实例,其中一个我没有看到,另一个我没有改变。基本上,我做的是图形选择,我做的是:

    this.graphSelectionGUI = (String)graphSelection.getSelectedItem();
    

    然后在nextActionPerformed中我做到了:

    new DefineEquation_1(graphSelectionGUI).setVisible(true);
    

    接下来,在另一个类(DefineEquation)中,我使用了我的构造函数并执行了以下操作:

    public DefineEquation(String graphSelected) {
        this.graphSelected = graphSelected;
        initComponents();
        selectedGraph.setText(graphSelected);
    }
    

    最后,我哭着意识到我给你们带来了多少麻烦,我是多么愚蠢,赞美上帝

    抱歉打扰了大家,我的坏朋友

  3. # 3 楼答案

    如果您只是习惯于将数据发送到DefineEquation类,那么应该在nextActionPerformed中使用带String参数的构造函数:

        new DefineEquation((String)graphSelection.getSelectedItem()).setVisible(true);
    

    而不是:

        new DefineEquation().setVisible(true);
    

    此外,你还需要让你的建造师:

    public DefineEquation(String graphSelected) {
        this.graphSelected = graphSelected;
        initComponents();
    }
    

    因为现在如果没有initComponents(),它将显示空帧。 最后,您需要在DefineEquation类中setText()JTextField,例如:

     selectedGraph = new javax.swing.JTextField(graphSelected);
    

    不要使用addItem()方法,也不要重写它,因为它会创建新的DefineEquation对象,这是不必要的,甚至是有害的。这样,在新的框架中,它会显示带有选定文本的JTextField。至少如果我正确理解了你的问题,这对我是有效的

    然而,我宁愿使用enums而不是普通的String,因为它们更可靠。您的函数集是常量,因此您可以创建例如:

    public enum Functions {NONE,LINEAR,BILINEAR,QUADRIATIC,CUBIC,EXPONENTIAL;}
    

    这需要更改构造函数和JComboBox内容,但您可以在整个应用程序中使用它。Tou可以在需要String显示的地方调用toString()name(),但在事件处理中使用枚举等。 我认为你也应该重新考虑你对多个JFrame的处理方法,正如评论中所建议的那样。我也不建议这样做,但这取决于你。 祝你好运

    编辑

    如果不想更改DefineEquation中的initComponents(),仍然可以这样修改addItem()

    public void addItem(){
        selectedGraph.setText(graphSelected);
    }
    

    然后在构造函数中调用call addItem(),用所选文本填充JTextField。 或者可以将graphSelected作为方法的参数传递,如果是这样的话,它不必是类字段