- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我花了一些时间浏览 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“窗口”结合。
概念图:
编辑 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/
Java 专家需要您的帮助。 今天我在一次采访中被问到这个问题,但我无法解决。所以我需要一个解决方案来解决这个问题; 反转字符串 Input : Hello, World! Output : oll
目标:单击按钮并将成分作为单独的项目添加到数组中。 当前设置: 这给出:蓝莓芒果柠檬汁 然后我希望能够通过单击按钮将成分作为单独的项目添加到数组中: var allI
如何编写正则表达式来匹配它(参见箭头): "this is a ->'' this is a "test' there is another "test' 第二种情况 /\b'/ Regex Demo
我有一个数组,其中包含有限数量的项目。我想随机删除项目,直到所有项目都被使用过一次。 示例 [1,2,3,4,5] 使用了随机数 5,所以我不想再这样了。使用了随机数 2,所以我不想再这样了。等等..
首先,抱歉,如果这太主观了,我只是不知道还能怎么问/去哪里问。 无论如何,鉴于我最近的所有问题,我准备很快发布一个 Android 应用程序,并且大部分测试都是在我的手机 Droid 上完成的。我真的
这可能不是这个问题的正确位置,如果不合适请随意移动它。我标记为 Delphi/Pascal 因为这是我在 atm 中工作的内容,但这可能适用于我猜的所有编程。 无论如何,我正在做一些代码清理,并考虑将
我像这样分隔了其余 api 的路由。有没有更好的方法来组织路由器?还是我现在的做法没问题? app.js app.use('/api/auth',auth); 应用程序/ Controller /au
我在 2 个单独的工作表中包含以下数据: 表1: A B C D a ff dd ff ee b 12 10 10 12 表2: A B C
我正在使用 jQuery,并在位于单独 HTML 文件中的表中获取了几行。单击时,每一行都会成功重定向到本地 HTML 文件。 (使用window.location) 我想要实现的目标 我想要完成的是
我有重叠背景图像的问题,当它们重叠时会导致阴影比不重叠时更暗,从而产生不均匀的阴影。 我有一个高度灵活的盒子,带有一些透明的背景图像和阴影以创建漂亮的边框。盒子本质上是 3 个元素。 您可以在此处找到
按照正常的微服务框架,我们希望将每个微服务放入其自己的 git 存储库中,然后为 Service Fabric 项目创建一个存储库。当我们更新其中一个微服务时,Service Fabric 项目将仅重
我想将多个片段嵌入到一个指令中。这是我的设置方式。 Everyone Development (3)
我希望在保留原件的同时将多个文件 gzip 到一个目录中(到多个 .gz 文件中)。 我可以使用这些命令来处理单个文件: find . -type f -name "*cache.html" -exe
有没有办法分别知道每个 Eclipse 插件消耗了多少内存? 最佳答案 进行堆转储并使用例如分析它Eclipse Memory Analyser . 如需更多信息,请参阅 Analyzing Equi
我们使用cusrom插件并以这种方式定义脚本(这是一个近似的伪代码): //It is common part for every script (1) environments { "env1"
我在控制台应用程序中托管了一个集线器,并有一个 WPF 应用程序连接到它。它工作得很好。然后我将集线器移到一个单独的项目中,并将主机的引用添加到新项目中。现在我收到 500 错误,没有其他详细信息。
是否可以在单独的 JAR 文件中为 JavaBean 构建类?具体来说,JavaBean 在一个 JAR 文件中具有 Bean 和 BeanInfo 类,而自定义属性编辑器类位于另一个 JAR 文件中
好的,所以我有一个 MAF 应用程序,它在单独的应用程序域中加载每个插件。这非常适合我的需要,因为它允许我在运行时动态卸载和重新加载我的插件。 问题是,我需要能够在子应用域中处理未处理的异常,捕获它,
在参加在线数据库类(class)(针对初学者)时,我注意到一个问题,我必须查找涉及...至少两个不同值的查询...例如, ELMASRI 书中的 COMPANY 数据库指出:查找至少从事两个不同项目的
(首先:我已经尝试了涉及边距、边框等的所有选项。) Link to problematic page. Link to similarly constructed, non-problematic p
我是一名优秀的程序员,十分优秀!