Accessing JComboBox data from separate JForm - java

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

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 called ShowSelectionPanel, 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:
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();
}
}
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:
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
}
}
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:
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);
}
}
The whole thing with some additional code to allow movement through the "cards" could look something like this:
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();
}
}
}
}

If you just wont to send data to DefineEquation class, you should use your constructor with String argument in nextActionPerformed:
new DefineEquation((String)graphSelection.getSelectedItem()).setVisible(true);
instead of:
new DefineEquation().setVisible(true);
Also you need to chenge you constructor to:
public DefineEquation(String graphSelected) {
this.graphSelected = graphSelected;
initComponents();
}
Because right now without initComponents() it will display empty frame.
At last, you need to setText() to JTextField in DefineEquation class, for example by:
selectedGraph = new javax.swing.JTextField(graphSelected);
Do not use addItem()method, or rewrite it, becouse it creates new DefineEquation object which is unnecessary an even harmful. This way in new frame it display JTextField with chosen text. It worked for me, at least if I understood your problem correctly.
However, I would rather use enums instead of plain String, as they are more reliable. Your function set is constant, so you can create for example:
public enum Functions {NONE,LINEAR,BILINEAR,QUADRIATIC,CUBIC,EXPONENTIAL;}
This will required change of constructor, and JComboBox content, but you would be able to use it in whole application. Tou can call toString() or name() where you need String 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() in DefineEquation, you can still modify addItem() like this:
public void addItem(){
selectedGraph.setText(graphSelected);
}
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.

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:
this.graphSelectionGUI = (String)graphSelection.getSelectedItem();
Then in nextActionPerformed I did:
new DefineEquation_1(graphSelectionGUI).setVisible(true);
Following this, in the other class (DefineEquation), I took my constructor and did this:
public DefineEquation(String graphSelected) {
this.graphSelected = graphSelected;
initComponents();
selectedGraph.setText(graphSelected);
}
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.

Related

How to access value from one JDialog to another? [duplicate]

How do I wire output to paneWithList?
PaneWithList has a listener on its JList so that the selected row is output to the console. How can I direct that output to the JTextPane on output?
Could PaneWithList fire an event which Main picks up? Would PropertyChangeSupport suffice?
Main.java:
package dur.bounceme.net;
import javax.swing.JTabbedPane;
public class Main {
private static JTabbedPane tabs;
private static PaneWithList paneWithList;
private static PaneWithTable paneWithTable;
private static Output output;
public static void main(String[] args) {
tabs = new javax.swing.JTabbedPane();
paneWithList = new PaneWithList();
paneWithTable = new PaneWithTable();
tabs.addTab("list", paneWithList);
tabs.addTab("table", paneWithTable);
tabs.addTab("output", output);
}
}
Here's an example using the observer pattern, also seen here, here and here. Note that it would also be possible to listen to the combo's model.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
/**
* #see http://en.wikipedia.org/wiki/Observer_pattern
* #see https://stackoverflow.com/a/10523401/230513
*/
public class PropertyChangeDemo {
public PropertyChangeDemo() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new ObserverPanel());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PropertyChangeDemo example = new PropertyChangeDemo();
}
});
}
}
class ObserverPanel extends JPanel {
private JLabel title = new JLabel("Value received: ");
private JLabel label = new JLabel("null", JLabel.CENTER);
public ObserverPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObserverPanel"));
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(title);
panel.add(label);
this.add(panel);
ObservedPanel observed = new ObservedPanel();
observed.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(ObservedPanel.PHYSICIST)) {
String value = e.getNewValue().toString();
label.setText(value);
}
}
});
this.add(observed);
}
}
class ObservedPanel extends JPanel {
public static final String PHYSICIST = "Physicist";
private static final String[] items = new String[]{
"Alpher", "Bethe", "Gamow", "Dirac", "Einstein"
};
private JComboBox combo = new JComboBox(items);
private String oldValue;
public ObservedPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObservedPanel"));
combo.addActionListener(new ComboBoxListener());
this.add(combo);
}
private class ComboBoxListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
String newValue = (String) combo.getSelectedItem();
firePropertyChange(PHYSICIST, oldValue, newValue);
oldValue = newValue;
}
}
}
I'd be use JMenu with JMenuItems with contents layed by using CardLayout rather than very complicated JTabbedPane(s)
For my own reference, and for anyone using the Netbeans GUI builder, this works so far as it goes:
The PanelWithList class:
package dur.bounceme.net;
public class PanelWithList extends javax.swing.JPanel {
public PanelWithList() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jList1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jList1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2)
.addComponent(jScrollPane1))
.addContainerGap(166, Short.MAX_VALUE))
);
}// </editor-fold>
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
row();
}
private void jList1KeyReleased(java.awt.event.KeyEvent evt) {
row();
}
// Variables declaration - do not modify
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
private void row() {
Object o = jList1.getSelectedValue();
String s = (String)o;
jTextArea1.setText(s);
this.firePropertyChange("list", -1, 1);
}
}
and Frame.java as a driver:
package dur.bounceme.net;
public class Frame extends javax.swing.JFrame {
public Frame() {
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() {
jTabbedPane1 = new javax.swing.JTabbedPane();
panelWithList1 = new dur.bounceme.net.PanelWithList();
panelWithTable1 = new dur.bounceme.net.PanelWithTable();
newJPanel1 = new dur.bounceme.net.PanelWithCombo();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panelWithList1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
panelWithList1PropertyChange(evt);
}
});
jTabbedPane1.addTab("tab1", panelWithList1);
jTabbedPane1.addTab("tab2", panelWithTable1);
jTabbedPane1.addTab("tab3", newJPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 937, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 555, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void panelWithList1PropertyChange(java.beans.PropertyChangeEvent evt) {
System.out.println("panelWithList1PropertyChange ");
}
/**
* #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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane jTabbedPane1;
private dur.bounceme.net.PanelWithCombo newJPanel1;
private dur.bounceme.net.PanelWithList panelWithList1;
private dur.bounceme.net.PanelWithTable panelWithTable1;
// End of variables declaration
}
The key being that panelWithList1PropertyChange is the listener on 'panelWithList' itself.
Because PanelWithList.firePropertyChange("list", -1, 1); cannot send Object nor String that I see, I'm not exactly sure how to get the value selected all the way from the JList up to the JFrame.
Hmm, well the API says yes it can send Objects. Have to check that out.
I think it's necessary to get some info about the model which the JList is using up to the JFrame. However, doesn't that break MVC? Or maybe that's the wrong approach.

send a input String from JPanel 1 to JPanel2 [duplicate]

How do I wire output to paneWithList?
PaneWithList has a listener on its JList so that the selected row is output to the console. How can I direct that output to the JTextPane on output?
Could PaneWithList fire an event which Main picks up? Would PropertyChangeSupport suffice?
Main.java:
package dur.bounceme.net;
import javax.swing.JTabbedPane;
public class Main {
private static JTabbedPane tabs;
private static PaneWithList paneWithList;
private static PaneWithTable paneWithTable;
private static Output output;
public static void main(String[] args) {
tabs = new javax.swing.JTabbedPane();
paneWithList = new PaneWithList();
paneWithTable = new PaneWithTable();
tabs.addTab("list", paneWithList);
tabs.addTab("table", paneWithTable);
tabs.addTab("output", output);
}
}
Here's an example using the observer pattern, also seen here, here and here. Note that it would also be possible to listen to the combo's model.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
/**
* #see http://en.wikipedia.org/wiki/Observer_pattern
* #see https://stackoverflow.com/a/10523401/230513
*/
public class PropertyChangeDemo {
public PropertyChangeDemo() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new ObserverPanel());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PropertyChangeDemo example = new PropertyChangeDemo();
}
});
}
}
class ObserverPanel extends JPanel {
private JLabel title = new JLabel("Value received: ");
private JLabel label = new JLabel("null", JLabel.CENTER);
public ObserverPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObserverPanel"));
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(title);
panel.add(label);
this.add(panel);
ObservedPanel observed = new ObservedPanel();
observed.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(ObservedPanel.PHYSICIST)) {
String value = e.getNewValue().toString();
label.setText(value);
}
}
});
this.add(observed);
}
}
class ObservedPanel extends JPanel {
public static final String PHYSICIST = "Physicist";
private static final String[] items = new String[]{
"Alpher", "Bethe", "Gamow", "Dirac", "Einstein"
};
private JComboBox combo = new JComboBox(items);
private String oldValue;
public ObservedPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObservedPanel"));
combo.addActionListener(new ComboBoxListener());
this.add(combo);
}
private class ComboBoxListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
String newValue = (String) combo.getSelectedItem();
firePropertyChange(PHYSICIST, oldValue, newValue);
oldValue = newValue;
}
}
}
I'd be use JMenu with JMenuItems with contents layed by using CardLayout rather than very complicated JTabbedPane(s)
For my own reference, and for anyone using the Netbeans GUI builder, this works so far as it goes:
The PanelWithList class:
package dur.bounceme.net;
public class PanelWithList extends javax.swing.JPanel {
public PanelWithList() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jList1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jList1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2)
.addComponent(jScrollPane1))
.addContainerGap(166, Short.MAX_VALUE))
);
}// </editor-fold>
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
row();
}
private void jList1KeyReleased(java.awt.event.KeyEvent evt) {
row();
}
// Variables declaration - do not modify
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
private void row() {
Object o = jList1.getSelectedValue();
String s = (String)o;
jTextArea1.setText(s);
this.firePropertyChange("list", -1, 1);
}
}
and Frame.java as a driver:
package dur.bounceme.net;
public class Frame extends javax.swing.JFrame {
public Frame() {
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() {
jTabbedPane1 = new javax.swing.JTabbedPane();
panelWithList1 = new dur.bounceme.net.PanelWithList();
panelWithTable1 = new dur.bounceme.net.PanelWithTable();
newJPanel1 = new dur.bounceme.net.PanelWithCombo();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panelWithList1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
panelWithList1PropertyChange(evt);
}
});
jTabbedPane1.addTab("tab1", panelWithList1);
jTabbedPane1.addTab("tab2", panelWithTable1);
jTabbedPane1.addTab("tab3", newJPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 937, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 555, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void panelWithList1PropertyChange(java.beans.PropertyChangeEvent evt) {
System.out.println("panelWithList1PropertyChange ");
}
/**
* #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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane jTabbedPane1;
private dur.bounceme.net.PanelWithCombo newJPanel1;
private dur.bounceme.net.PanelWithList panelWithList1;
private dur.bounceme.net.PanelWithTable panelWithTable1;
// End of variables declaration
}
The key being that panelWithList1PropertyChange is the listener on 'panelWithList' itself.
Because PanelWithList.firePropertyChange("list", -1, 1); cannot send Object nor String that I see, I'm not exactly sure how to get the value selected all the way from the JList up to the JFrame.
Hmm, well the API says yes it can send Objects. Have to check that out.
I think it's necessary to get some info about the model which the JList is using up to the JFrame. However, doesn't that break MVC? Or maybe that's the wrong approach.

Having trouble moving a jButton

I'm trying to use Matisse in NetBeans to create a simple game...like Myst. I just want it to display a Frame that has things like a text field and buttons/inventory on the right. I can do that. Then I created a Jpanel that displays on the Frame. I've input some pictures and created a set of cards to make visible and invisible when needed. Each card/scene needs to have buttons that will be different for each scene. Basically I want to make transparent buttons for the user to press that do things (i.e. move to next picture/scene, find a key, etc...). I can create different buttons in each picture, but I can't seem to move them anywhere. I have a suspicion it's due to Matisse, but I don't know.
Here is some of the code, I'm sure it's crude as it's my first implementation of anything in Java. At the very bottom in the Scene to display I've added a button, that displays. I pretty much know now that the setBounds won't work due to the way position works...how would I then place it somewhere. Right now it just displays at the top mid of the picture.
SceneFrame:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import scene.SecondPanel;
import scene.FirstPanel;
import scene.Scene;
import javax.swing.JButton;
public class SceneFrame extends javax.swing.JFrame {
private FirstPanel sceneP;
private SecondPanel sceneSP;
/**
* Creates new form SceneFrame
*/
public SceneFrame() {
initComponents();
addCards();
}
public void addCards() {
sceneP = new FirstPanel();
SceneManager.add("SecondPanel", sceneP);
sceneSP = new SecondPanel();
SceneManager.add("FirstPanel", sceneSP);
sceneP.setVisible(false);
}
/**
* 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() {
SceneManager = new scene.ScenePanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout SceneManagerLayout = new javax.swing.GroupLayout(SceneManager);
SceneManager.setLayout(SceneManagerLayout);
SceneManagerLayout.setHorizontalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 517, Short.MAX_VALUE)
);
SceneManagerLayout.setVerticalGroup(
SceneManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 421, Short.MAX_VALUE)
);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addComponent(SceneManager, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(SceneManager, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 97, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
sceneP.setVisible(false);
//SceneManager.showScene("SecondPanel");
sceneSP.setVisible(true);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sceneSP.setVisible(false);
//SceneManager.showScene("FirstPanel");
sceneP.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(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SceneFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SceneFrame.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 SceneFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel SceneManager;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
// End of variables declaration
}
Scene:
package scene;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Image;
import javax.swing.ImageIcon;
public abstract class Scene extends JPanel {
public Image image;
private String sceneName;
public Scene(String cn) {
setName(cn);
this.setSize(600, 600);
this.setBackground(Color.WHITE);
}
public String getCardName() {
return sceneName;
}
public abstract void addControlButtons();
// public abstract void implementControlButtons();
}
A Panel to display:
/**
* Creates a new ForestScene Object.
*/
public SecondPanel() {
super("SecondPanel");
JButton Button2 = new JButton("SwagCity");
try {
image = (new ImageIcon(getClass().getResource("/resources/ForestPath.jpg"))).getImage();
} catch (Exception e) {/*How to handle?*/
}
this.addControlButtons();
}
#Override
public void addControlButtons(){
JButton bButton = new JButton("bButton");
//bButton.setBounds(200, 300, 500, 600); //How to display where I want?
bButton.setAlignmentX(1000);
this.add(bButton);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Graphics2D g2 = (Graphics2D) g;
if (image != null) {
boolean val = g.drawImage(image, 0, 0, 800, 600, this);
} else {
System.out.println("Image not found");
}
}
}
You need to add JFrame.frame.setLayout(null) so that you can adjust your fields(button,textfields) on to the frame.I too had a similar problem
I've figured out that it must be the layoutManager confusing something. If i set: this.setLayout(null); I can then set the bounds of the button and it displays where and how I want. I apologize if the question did not have enough information, but I did not know myself anymore than I told you. If anyone has anything to add about what I did, I'll be glad to select that as my answer.

JPanel dynamically generate outside from its original location

I'm dynamically generating some text boxes and labels inside a JPanel but when I place that panel inside a JTabbedPane it's not generate inside its original location. it always go to somewhere else.
Code inside JFrame class constructor:
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Code inside a JButton:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
The button is use to generate text boxes and labels dynamically. jPanel1 is a panel placed inside a frame. its works perfectly with directly placed inside a frame but after it is placed inside a tabbed pane it's messing around.
Is there a method to refresh panel and remove components inside it after generating components inside it?
here is the complete Jframe class:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author sajithru
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
private JPanel panel;
public DynamicTextboxes() {
initComponents();
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 206, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 258, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab1", jPanel1);
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(190, 190, 190)
.addComponent(jButton1)
.addContainerGap(216, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
}
/**
* #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(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.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 DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
I suspect that you are using setBounds(), or something similar, to position components in a Container that has some (default) layout lying in wait for your call to revalidate(). Instead, invoke pack() on the enclosing Window before calling setVisible().
Addendum: I tried using pack() … but result is still the same.
Your layout is cutting off the new rows. The example below uses pack() to resize the enclosing Window. This related example illustrates revalidate() and repaint(). Also consider using a JScrollPane, seen here.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see https://stackoverflow.com/a/17165034/230513
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
public DynamicTextboxes() {
initComponents();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel(new GridLayout(0, 1));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(createPanel());
jTabbedPane1.addTab("tab1", jPanel1);
add(jTabbedPane1);
JPanel p = new JPanel();
p.add(jButton1);
add(p, BorderLayout.SOUTH);
pack();
setLocationByPlatform(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.add(createPanel());
pack();
}
private JPanel createPanel() {
JPanel p = new JPanel();
JLabel lbl = new JLabel();
lbl.setText("Label");
p.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
p.add(txt);
return p;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}

Java refreshing second form

I have two forms. First one is to decide numbers of button by using jslider. Second form is to display jbuttons according to jslider value. When i click jbutton2, the second form shows and display buttons. It is working perfectly. However, I want to create jbutton on the second form without clicking jbutton2 in the first form.
Instead, when I change jslider, it should create jbuttons on the second form at the run time and once i change jslider it should create that amount of button again on the second form and refreshing the second form button numbers according to jslider value.
I have tried revalidate();, repaint(); but they do not work, they dont refresh the second form.
So, How can I refresh second form when the jslider ,that is on the first form, changes ? Please help.....
Edit:I am using default Jframe of netbeans....
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class NewJFrame7 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame7
*/
public NewJFrame7() {
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() {
jSlider1 = new javax.swing.JSlider();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSlider1.setMajorTickSpacing(2);
jSlider1.setMaximum(20);
jSlider1.setMinimum(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setToolTipText("");
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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(29, 29, 29)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(273, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(262, 262, 262)
.addComponent(jButton2)
.addContainerGap(262, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(168, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addComponent(jButton2)
.addContainerGap(139, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
form2 = true;
new NewJFrame8().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(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.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 NewJFrame7().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JSlider jSlider1;
// End of variables declaration
}
2.form
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class NewJFrame8 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame8
*/
public NewJFrame8() {
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() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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(371, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(242, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #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(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.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 NewJFrame8().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
One layout constraint (BorderLayout.CENTER) to place them, and one component to appear therein. (With apologies to Tolkien.)
Do check this sample Program, is this what you need. revalidate() and repaint() is what works here for this.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
for (int i = 0; i < value; i++)
{
ButtonPanel.panel.add(new JButton("JButton " + i));
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private JButton[] buttonArray;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(button.getText());
}
};
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
buttonArray = new JButton[value];
for (int i = 0; i < value; i++)
{
buttonArray[i] = new JButton(String.valueOf(i));
buttonArray[i].addActionListener(actionButton);
ButtonPanel.panel.add(buttonArray[i]);
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
For your statement this.buttonArray[i].addActionListener(this);, the reason as to why this is not working, is because, you are inside the object of anonymous class new ChangeListener(), which doesn't have anything named buttonArray[i] inside itself, it's the Instance Variable of SliderExample class, so either place an object of SliderExample class or if you are referring to your code, then use the Object of the class which initializes the array like inside inside NewFrame8 you had written JButton[] buttonArray = new JButton[120];, so use NewFrame8's object instead of this to refer to the buttonArray[i] thingy.

Categories

Resources