从单独的JForm

时间:2015-05-17 16:01:40

标签: java swing netbeans jframe jcombobox

我花了一些时间浏览Stack Overflow和互联网寻找我的问题的答案,但我发现所有的答案都很难理解,我不确定是否有任何问题与我的问题有关,所以我决定在正确的背景下需要帮助。

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

我有两个类,GraphEquationSolverGUI和DefineEquation。我正在使用Netbeans IDE和GraphEquationSolverGUI是我的"项目。"

GraphEquationSolverGUI:

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中。接下来的另一个代码是我尝试创建一个对象并通过它传递数据,因为我还没有和它们一起工作一段时间,我对它们有点生气,如果我让你哭的话,对不起。

DefineEquation:

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,其中我将String转换为明显多余的String。我这样做是为了以防万一,这是多余的,对不起让你畏缩。

我知道这可能很难理解,你可能会发现很难理解我在问什么。简单地说,如何将数据从一个JFrame JComboBox传递到单独的JFrame中的JTextField?我会使用对象吗?如果可以的话,请尽量让我通过它,我很困惑。如果您想阅读所有内容,我会在下面粘贴我的所有代码。

GraphEquationSolverGUI:

/*
* 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                   
}

DefineEquation:

/*
 * 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                   
}

你会注意到我试图&#34;延伸&#34;我的第一个JFrame,但这导致了第二个JFrame&#34;窗口&#34;以某种方式与第一个JFrame&#34;窗口结合。&#34;

概念图片:

enter image description here

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

编辑2:我正在尝试使用m.cekiera的答案,在回答之前参考他的回答,因为它可能会有所帮助。

编辑3:仍然卡住并且需要详细的帮助,很抱歉要这么苛刻,但我无法解决这个问题。

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

所以这是SelectSolutionsQuadratic类:

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

这是DefineEquationQuadratic:

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

所以基本上我很困惑为什么我可以将DefineEquationQuadratic中的值发送到SelectSolutionsQuadratic,用System.out.println()输出它;但将文本字段设置为该值

3 个答案:

答案 0 :(得分:3)

我建议您创建两个JPanel类,一个用于保存JComboBox,另一个用于显示或以其他方式需要结果。假设你已经完成了这个并且调用了第一个类HoldsComboBoxPanel,并且你的第二个类被称为ShowSelectionPanel,那么你将给HoldsComboBoxPanel两个方法,一个用于获取当前选择,一个是“getter”方法和另一个允许外部类将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来允许你交换JPanels,有一个公共方法允许外部类交换“card”JPanels,它可以同时保存HoldsComboBoxPanel字段和ShowSelectionPanel字段,并且可以通过将ActionListener添加到它来链接它们。像这样的组合框:

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

答案 1 :(得分:2)

如果您不想将数据发送到DefineEquation课程,则应在String中使用带有nextActionPerformed参数的构造函数:

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

而不是:

    new DefineEquation().setVisible(true);

您还需要将构造函数变为:

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

因为现在没有initComponents()它会显示空框架。 最后,您需要在setText()课程中JTextFieldDefineEquation,例如:

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

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

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

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

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

<强> 修改

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

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

但是你在构造函数中调用addItem(),用你选择的文本填充你的JTextField。 或者你可以传递graphSelected作为方法的参数,如果是的话,它不必是一个类字段。

答案 2 :(得分:-1)

所以我真的很蠢,创造了两个实例,其中一个是我没有看到的,另一个我是,但没有改变。基本上我所做的是在graphSelectionActionPerformed我做了:

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

然后在nextActionPerformed我做了:

new DefineEquation_1(graphSelectionGUI).setVisible(true);

在此之后,在另一个类(DefineEquation)中,我接受了我的构造函数并执行了此操作:

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

最后,我泪流满面地意识到我给你们带来了多少麻烦,我是多么愚蠢,赞美主人!

抱歉让所有人感到不安,不好。