I've spent a bit of time browsing Stack Overflow and the internet looking for the answer to my question, but I found all the answers hard to understand and I was quite unsure if any of them related to my problem, so I decided I needed help in the right context.
I am creating a program that will give a series of solutions based on a particular type of graph inputted. I am sincerely struggling with taking the data from my JComboBox in the first JFrame, and displaying it in the second.
I have two classes, GraphEquationSolverGUI and DefineEquation. I am using the Netbeans IDE and GraphEquationSolverGUI is my "project."
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);
This is the JComboBox in which I want the selection to send data to another class. The JComboBox is called graphSelection. You will notice the the commented text is me setting a JTextField to the value of the JComboBox, this is inside of this JForm and was used by myself to test to make sure the data was being input right, it works and I can display the data in this same JFrame. The other code following is my attempt to create an object and pass the data through it, I'm a bit rusty with objects as I haven't worked with them for a while, sorry if I make you cry.
DefineEquation:
public DefineEquation(String graphSelected) {
this.graphSelected = graphSelected;
} //If anyone cares here is my constructor for the object
public void addItem(String graphSelectedString1){
DefineEquation graphSelectedObj = new DefineEquation(graphSelected);
String graphSelectedStringMAIN = graphSelectedString1.toString();
selectedGraph.setText(graphSelectedStringMAIN);
}
The above is the method I created to add the data to a JTextField called selectedGraph. You will notice I have graphSelectedString1 and graphSelectedStringMAIN in which I convert a String to a String which is obviously redundant. I did this just in case, it is redundant, sorry for making you cringe.
I understand that this may be hard to follow, and you may find it hard to understand what I am asking. So simply put, how would I pass data from one JFrame JComboBox to a JTextField in a separate JFrame? Would I use Objects? Please try to walk me through it if you can, I am very confused. I will paste all my code below if you wish to read through everything.
GraphEquationSolverGUI:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
/**
*
* @author MatthewAlanTroutman
*/
public class GraphEquationSolverGUI extends javax.swing.JFrame {
/**
* Creates new form GraphEquationSolverGUI
*/
public GraphEquationSolverGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSpinner1 = new javax.swing.JSpinner();
welcome = new javax.swing.JLabel();
programDescription = new javax.swing.JLabel();
graphsOffered = new javax.swing.JLabel();
linear = new javax.swing.JLabel();
bilinear = new javax.swing.JLabel();
quadratic = new javax.swing.JLabel();
cubic = new javax.swing.JLabel();
exponential = new javax.swing.JLabel();
graphSelectionText = new javax.swing.JLabel();
graphSelection = new javax.swing.JComboBox();
help = new javax.swing.JButton();
close = new javax.swing.JButton();
next = new javax.swing.JButton();
graphSelectedTextField = new javax.swing.JTextField();
graphSelectedLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("GraphEquationSolver");
setBackground(new java.awt.Color(255, 255, 255));
welcome.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
welcome.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
welcome.setText("Welcome");
welcome.setPreferredSize(new java.awt.Dimension(800, 100));
programDescription.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
programDescription.setText("You can use this program to find a variety of solutions for different types of graphs, please select a graph to begin");
programDescription.setPreferredSize(new java.awt.Dimension(800, 75));
graphsOffered.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
graphsOffered.setText("Graphs we offer:");
linear.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
linear.setText("- Linear");
bilinear.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
bilinear.setText("- Bilinear");
quadratic.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
quadratic.setText("- Quadratic");
cubic.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
cubic.setText("- Cubic");
exponential.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
exponential.setText("- Exponential");
graphSelectionText.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
graphSelectionText.setText("Please select your graph");
graphSelection.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Linear", "Bilinear", "Quadratic", "Cubic", "Exponential" }));
graphSelection.setToolTipText("");
graphSelection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
graphSelectionActionPerformed(evt);
}
});
help.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
help.setText("Help");
close.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
close.setText("Close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
next.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
next.setText("Next");
next.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextActionPerformed(evt);
}
});
graphSelectedTextField.setEditable(false);
graphSelectedLabel.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
graphSelectedLabel.setText("Graph Selected");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(240, 240, 240))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(240, 240, 240)
.addComponent(programDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(184, 184, 184)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(exponential)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(graphsOffered)
.addComponent(linear)
.addComponent(bilinear)
.addComponent(quadratic)
.addComponent(cubic))
.addGap(311, 311, 311)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(graphSelectionText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(graphSelection, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(graphSelectedTextField)
.addComponent(graphSelectedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addGroup(layout.createSequentialGroup()
.addGap(231, 231, 231)
.addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(240, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(programDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(graphsOffered)
.addComponent(graphSelectionText))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(graphSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(linear)
.addComponent(graphSelectedLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(bilinear)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(quadratic))
.addComponent(graphSelectedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cubic)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(exponential)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 219, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(help, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(next, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(169, 169, 169))))
);
graphSelection.getAccessibleContext().setAccessibleName("");
help.getAccessibleContext().setAccessibleName("help");
close.getAccessibleContext().setAccessibleName("close");
pack();
}// </editor-fold>
private void graphSelectionActionPerformed(java.awt.event.ActionEvent evt) {
String graphSelectionGUI = (String)graphSelection.getSelectedItem();
graphSelectedTextField.setText(graphSelectionGUI);
//DefineEquation graphSelectedObj = new DefineEquation(graphSelectionGUI);
//graphSelectedObj.addItem(graphSelectionGUI);
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void nextActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
new DefineEquation().setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GraphEquationSolverGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GraphEquationSolverGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel bilinear;
private javax.swing.JButton close;
private javax.swing.JLabel cubic;
private javax.swing.JLabel exponential;
private javax.swing.JLabel graphSelectedLabel;
private javax.swing.JTextField graphSelectedTextField;
private javax.swing.JComboBox graphSelection;
private javax.swing.JLabel graphSelectionText;
private javax.swing.JLabel graphsOffered;
private javax.swing.JButton help;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JLabel linear;
private javax.swing.JButton next;
private javax.swing.JLabel programDescription;
private javax.swing.JLabel quadratic;
private javax.swing.JLabel welcome;
// End of variables declaration
}
DefineEquation:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
/**
*
* @author MatthewAlanTroutman
*/
public class DefineEquation extends javax.swing.JFrame {
//public class DefineEquation extends GraphEquationSolverGUI {
public String graphSelected;
/**
* Creates new form DefineEquation
*/
public DefineEquation() {
initComponents();
}
public DefineEquation(String graphSelected) {
this.graphSelected = graphSelected;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
selectedGraph = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
selectedGraph.setEditable(false);
selectedGraph.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectedGraphActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(435, 435, 435)
.addComponent(selectedGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(596, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(selectedGraph, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(646, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void selectedGraphActionPerformed(java.awt.event.ActionEvent evt) {
}
public void addItem(String graphSelectedString1){
DefineEquation graphSelectedObj = new DefineEquation(graphSelected);
String graphSelectedStringMAIN = graphSelectedString1.toString();
selectedGraph.setText(graphSelectedStringMAIN);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DefineEquation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DefineEquation().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField selectedGraph;
// End of variables declaration
}
You will notice I tried to "extend" my first JFrame, but this resulted in the second JFrame "window" somehow combining with the first JFrame "window."
Conceptual images:
Edit 1: Is this the best way to go through with it? If so, how would I go about moving the data around? Objects are currently confusing me along with some non static and static problems which don't seem valid as I don't have anything static. If this is not the best way of doing it, what should I do? I'm going to bed, please comment with your suggestions and help, not only am I desperate, but I feel lost.
Edit 2: I am trying to work with what m.cekiera's answer was, refer to his answer before answering as it might be helpful.
Edit 3: Still stuck and talk in need of detailed help, sorry to be so demanding but I can't wrap my head around this.
Edit 4: I think I've found a significant breakthrough. I've figured out how to work around the issue, but I really think I need to understand this. Anyway, I've got a new class and a new text field for a different class. I still have the problem, I can't display a value of of the textfield, but for some reason I can output the same value. I guess it's easier shown
So this is the class SelectSolutionsQuadratic:
public void displayText(String textToSet) {
displayQuadraticEquation.setText(textToSet);
System.out.println(textToSet);
}
And this is 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);
}
So basically I'm just confused why I can send a value from DefineEquationQuadratic to SelectSolutionsQuadratic, output it with System.out.println(); but NOT set the textfield to be that value
So I was really dumb and had two instances created, one of which I was not viewing and the other of which I was but was not changing. Basically what I did was in graphSelectionActionPerformed I did:
Then in nextActionPerformed I did:
Following this, in the other class (DefineEquation), I took my constructor and did this:
And lastly I cried with tears realising how much trouble I gave you guys and how dumb I was, praise the lord!
Sorry for troubling everyone, my bad.
What I'm suggesting is that you create two JPanel classes, one that holds your JComboBox, and the other that displays or otherwise needs the results. Assuming you've done that and called the first class,
HoldsComboBoxPanel
, and your second class is calledShowSelectionPanel
, then you would give the HoldsComboBoxPanel two methods, one to get the current selection, a "getter" method, and another to allow outside classes to add an ActionListener to the combobox. For instance in brief, something like so:Your second class, the one that needs the data would have a setter method to allow outside classes the ability to push the combo selection into it. Assuming it had a JTextField called displayField that showed the selection, its code could look like so:
Then you'd have another class that used CardLayout and that allowed swapping between the view JPanels above, say called MainPanel. It could use the CardLayout to allow you to swap JPanels, have a public method to allow outside classes to swap "card" JPanels, and it would hold both a HoldsComboBoxPanel field and a ShowSelectionPanel field, and could link them by adding the ActionListener to the combobox like so:
The whole thing with some additional code to allow movement through the "cards" could look something like this:
If you just wont to send data to
DefineEquation
class, you should use your constructor withString
argument innextActionPerformed
:instead of:
Also you need to chenge you constructor to:
Because right now without
initComponents
() it will display empty frame. At last, you need tosetText()
toJTextField
inDefineEquation
class, for example by:Do not use
addItem()
method, or rewrite it, becouse it creates newDefineEquation
object which is unnecessary an even harmful. This way in new frame it displayJTextField
with chosen text. It worked for me, at least if I understood your problem correctly.However, I would rather use
enums
instead of plainString
, as they are more reliable. Your function set is constant, so you can create for example:This will required change of constructor, and
JComboBox
content, but you would be able to use it in whole application. Tou can calltoString()
orname()
where you needString
to display, but use enums in event handling, etc. I think you should also reconsider your approach to multiple JFrames, as suggested in comments. I also would not recommend that, but it is up to you. Good luck!EDIT
If you dont't want to change
initComponents()
inDefineEquation
, you can still modifyaddItem()
like this:but then you call call addItem() in constructor, to fill your JTextField with chosen text. Or you can pass
graphSelected
as argument of method, if so it don't have to be a class field.