gpt4 book ai didi

java - 从单独的 JForm 访问 JComboBox 数据

转载 作者:搜寻专家 更新时间:2023-11-01 02:42:36 25 4
gpt4 key购买 nike

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

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

我有两个类,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 中。下面的其他代码是我尝试创建一个对象并通过它传递数据,我对对象有点生疏,因为我已经有一段时间没有使用它们了,如果我让你哭了,我很抱歉。

定义方程:

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
}

定义方程:

/*
* 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:这是完成它的最佳方式吗?如果是这样,我将如何移动数据?对象目前让我感到困惑,还有一些非静态和静态问题,这些问题似乎无效,因为我没有任何静态问题。如果这不是最好的方法,我该怎么办?我要 sleep 了,请评论说出你的建议和帮助,我不仅绝望,而且感到迷茫。

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

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

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

所以这是 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() 输出它;但将文本字段设置为该值

最佳答案

我的建议是创建两个 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 并允许在上面的 View JPanel 之间交换的类,例如称为 MainPanel。它可以使用 CardLayout 来允许您交换 JPanel,有一个公共(public)方法来允许外部类交换“卡片”JPanel,并且它会同时包含 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();
}
}
}
}

关于java - 从单独的 JForm 访问 JComboBox 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com