当前位置: 首页 > 知识库问答 >
问题:

从单独的JForm访问JComboBox数据

云胤
2023-03-14

我花了一点时间浏览堆栈溢出和互联网寻找我的问题的答案,但是我发现所有的答案都很难理解,我不确定它们中是否有任何一个与我的问题相关,所以我决定我需要帮助正确的背景。

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

我有两个类,GraphEquationSolverGUI和定义方程。我使用的Netbean IDE和GraphEquationSolverGUI是我的"项目"。

图形方程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被称为图形选择。你会注意到评论的文本是我将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);
}

以上是我创建的将数据添加到名为selectedGaphJTextField的方法。您会注意到,我有图形选择字符串1和图形选择字符串主,其中我将字符串转换为字符串,这显然是多余的。我这样做只是为了以防万一,这是多余的,抱歉让你畏缩。

我知道这可能很难理解,你可能很难理解我在问什么。简单地说,我如何将数据从一个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“窗口”相结合

概念图像:

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

编辑2:我正在努力理解m.cekiera的答案,在回答之前参考他的答案,因为它可能会有所帮助。

编辑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个答案

凌智
2023-03-14

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

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

然后在nextActionPerformed中我做到了:

new DefineEquation_1(graphSelectionGUI).setVisible(true);

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

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

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

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

丌官淇
2023-03-14

如果您只是不想将数据发送到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。至少如果我正确理解了你的问题,这对我是有效的。

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

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

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

编辑

如果你不想改变定义方程中的initComponents(),你仍然可以这样修改addItem()

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

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

汪正卿
2023-03-14

我的建议是创建两个JPanel类,一个保存JComboBox,另一个显示或需要结果。假设您已经这样做了,并调用了第一个类,HoldsComboxPanel,第二个类叫做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();
         }
      }
   }
}
 类似资料:
  • 如何在java摆中从第二个JFrame获取数据?我有一个带有JLabel和JButton的帧。单击JButton时,它会打开另一个带有自定义日历的帧。我想选择日期(通过JButton)并将日期放在主JFrame的JLabel中。我不想创建第一帧的新实例,因为还有其他用户可能键入的我不想删除的信息。

  • 我使用单独的YAML可以轻松地停止一个容器,而不停止另一个容器。 为了解决这个任务,我使用了Docker-Compose的桥接网络功能。所以我使用了以下两个YAML: 和

  • 问题内容: 我有一个要求,即只能从本地主机访问mysql数据库。我必须实现一个可以访问数据库的servlet,以允许该系统中的其他服务器访问数据(servlet可以充当代理)。但是,此系统由一个远程服务器组成,该服务器下载执行以下语句的大部分数据: 有人可以建议我如何编写一个以有效方式流式传输此类数据的servlet吗(我是数据库新手)? 问题答案: 首先,我不建议为此使用servlet。有关正确

  • 我在第一个事务中运行以下查询: 然后是第二个,来自不同的连接,这是完全相同的。在,它正在等待。 然后我运行下面的代码来查看锁 它显示行锁(ROW SHARE,ROW EXCLUSVE),这很好。但我也看到了 根据文档来自: 通过ALTERTABLE、DROP TABLE、TRUNCATE、REINDEX、CLUSTER和VACUUM FULL命令获取。这也是未显式指定模式的lock TABLE语句

  • 我正在使用Guice在Java应用程序中创建一个单例。我在模块类中使用了以下方法: 在另一个类中,我尝试通过以下方式获取实例: 最后,我想从我的注入器访问应用程序中的相同实例,我尝试这样做: 这是在资源类和我的应用程序中从注入器共享实例的正确方法吗?

  • 问题内容: 我正在使用Java和TestNG框架为我的公司编写一些selenium自动UI测试。我正在类中定义驱动程序,并且我想在中实际初始化驱动程序并在方法中退出它。假设它们在不同的类中,Java的实现方式是什么?我知道如何使它在同一个类中工作,但不能在单独的类中工作。这是我的文件: 现在,我想拥有一个单独的Setup类和一个Teardown类。如果我要用相同的方式定义所有这些,则可以这样进行: