Java Swing Label not updating when called from outside class - java

I am trying to update a JTextBox with data from a serial port in java swing. The problem I am facing is that the JTextBox is not getting updated.
I tried repaint() and revalidate functions also but not use. I also tried putting the setText() inside a runnable. Nothing works. Please guide me in this.
public class PrinterUI extends javax.swing.JFrame{
/**
* Creates new form PrinterUI
*/
public PrinterUI() {
initComponents();
initOtherUI();
}
public void initOtherUI(){
menu = new ArrayList<javax.swing.JMenuItem>();
}
public void showSensorValueOnScreen(long id, int pres, int temp){
System.out.println(Long.toHexString(id));
sensorID = id;
System.out.println(Long.toHexString(sensorID));
opText.setText(Long.toHexString(sensorID));
}
/**
* 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() {
jMenu3 = new javax.swing.JMenu();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
opText = new javax.swing.JTextField();
jMenuBar1 = new javax.swing.JMenuBar();
printerMenuBar = new javax.swing.JMenu();
mobileMenuBar = new javax.swing.JMenu();
jMenu3.setText("jMenu3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Print");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jLabel1.setText("Sensor Output");
opText.setText("jTextField1");
opText.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
opTextPropertyChange(evt);
}
});
printerMenuBar.setText("Printer");
printerMenuBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
printerMenuBarMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
printerMenuBarMouseEntered(evt);
}
});
jMenuBar1.add(printerMenuBar);
mobileMenuBar.setText("Mobile");
jMenuBar1.add(mobileMenuBar);
setJMenuBar(jMenuBar1);
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(203, 203, 203)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jButton1))
.addContainerGap(236, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(108, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(opText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(jButton1)
.addGap(105, 105, 105))
);
getAccessibleContext().setAccessibleName("jLabel1");
pack();
}// </editor-fold>
private void printerMenuBarMouseClicked(java.awt.event.MouseEvent evt) {
System.out.println("clicked");
}
private void printerMenuBarMouseEntered(java.awt.event.MouseEvent evt) {
String[] portNames = null;
portNames = SerialPortList.getPortNames();
for (String string : portNames) {
System.out.println(string);
}
if (portNames.length == 0) {
System.out.println("There are no serial-ports");
} else {
SerialPort serialPort = new SerialPort("COM25");
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
PortReader portReader = new PortReader(serialPort);
serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
} catch (Exception e) {
System.out.println("There are an error on writing string to port т: " + e);
}
}
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
System.out.println("Print Click");
opText.setText(Long.toString(sensorID));
System.out.println(Long.toHexString(sensorID));
}
/**
* #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(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrinterUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrinterUI.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 PrinterUI().setVisible(true);
}
});
}
private List<javax.swing.JMenuItem> menu;
PrintService pservice = null;
public static long sensorID;
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu mobileMenuBar;
private javax.swing.JTextField opText;
private javax.swing.JMenu printerMenuBar;
// End of variables declaration
}
class PortReader implements SerialPortEventListener{
SerialPort serialPort;
public int[] incomingData = new int[20];
public int dataIndex=0;
public long sensorID=0;
public int pressure;
public int temperature;
public PortReader(SerialPort serialPort) {
this.serialPort = serialPort;
}
#Override
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readHexString();
for(int x=0;x<receivedData.length();x=x+2){
int data = Integer.parseInt(receivedData.substring(x, x+2),16);
//System.out.println(data);
if((dataIndex==0)&&(data==170)){
incomingData[dataIndex++]=data;
}else if(dataIndex>0){
incomingData[dataIndex++]=data;
if(dataIndex>=14){
dataIndex=0;
long tyreId =(long)(((int)incomingData[6])*16777216 + ((int)incomingData[7])*65536 + ((int)incomingData[8])*256 + ((int)incomingData[9]));
tyreId = tyreId & 0x00000000FFFFFFFFL;
int press = incomingData[10];
int temp = incomingData[11];
sensorID = tyreId;
pressure = press;
temperature = temp;
PrinterUI obj = new PrinterUI();
obj.showSensorValueOnScreen(sensorID, pressure, temperature);
System.out.println("ID: " + Long.toHexString(tyreId) + ", Pressure: " + pressure + ", Temperature: " + temperature);
}
}else{
dataIndex=0;
}
}
} catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
When a serial data is received, serialEvent is called in PortReader class which in turn calls the showSensorValueOnScreen() method in the PrinterUI class. The JTextBox widget doesnt gets updated.
But when a button on the UI is pressed, the JTextBox gets updated.
Why doesnt it get updated when I call it from outside the class?. Please help me out here.

I found out the issue. I am trying to update the UI from another class by creating a new object for the UI. The actual UI was created from void main using a different object.
I resolved it by passing the existing object to the class that was calling the UI update function.
Thank you for your help people.

Related

How to delete text from a JTextField when you press a JButton (JAVA)

My program has to print messages in the JTextField when the Resume Producers button is pressed, and it needs to delete the messages when the Resume Consumers is pressed.
The thing is that I don't know how to delete the messages when the Resume Consumers is pressed.
Code:
package buffer;
import java.util.ArrayList;
import javax.swing.JTextField;
public class Buffer
{
private String message;
private boolean full=false;
Topass pass = new Topass();
public ArrayList<String> list = new ArrayList<String> ();
JTextField tf;
String content="";
public Buffer(JTextField t1){
tf=t1;
}
public synchronized void put(String message)
{
list.add(message);
}
public synchronized void take(String message)
{
list.remove(message);
}
public synchronized void sendMessage(String msg)
{
while(full && list.size()>=30)
{
try
{
wait();
} catch (InterruptedException ex) { }
}
pass.look();
full=true;
message=msg;
list.add(message);
for(int i=0; i<list.size(); i++){
content=content+list.get(i);
}
tf.setText(content);
notifyAll();
}
public synchronized String receivesMessage()
{
while(!full)
{
try
{
wait();
} catch (InterruptedException ex) { }
}
pass.look();
full=false;
notifyAll();
return message;
}
}
package buffer;
import static java.lang.Thread.sleep;
import javax.swing.JButton;
public class Consumer extends Thread
{
private int numMessages;
private Buffer miBuffer;
private String readers;
public Consumer(String reader, Buffer miBuffer)
{
this.numMessages=numMessages;
this.miBuffer=miBuffer;
this.readers=reader;
}
#Override
public void run()
{
while(true){
try
{
sleep((int)(300+400*Math.random()));
} catch(InterruptedException e){ }
System.out.println(readers + " Has read " + miBuffer.receivesMessage());
}
}
}
package buffer;
import static java.lang.Thread.sleep;
import java.util.ArrayList;
public class Producer extends Thread
{
private String prefix;
private int numMessages;
private Buffer miBuffer;
public Producer(String prefix, int n, Buffer buffer)
{
this.prefix=prefix;
numMessages=n;
miBuffer=buffer;
}
public void run()
{
numMessages = 99;
for(int i=1; i<=numMessages; i++)
{
try
{
sleep((int)(500+400*Math.random()));
} catch(InterruptedException e){ }
miBuffer.sendMessage(prefix+i);
//miBuffer.meter(prefijo+i);
}
}
}
package buffer;
public class Topass
{
private boolean closed=false;
public synchronized void look()
{
while(closed)
{
try
{
wait();
} catch(InterruptedException ie){ }
}
}
public synchronized void open()
{
closed=false;
notifyAll();
}
public synchronized void closed()
{
closed=true;
}
}
package buffer;
import java.awt.Container;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import static jdk.nashorn.internal.objects.ArrayBufferView.buffer;
/**
*
* #author Bogdan
*/
public class DigitalBuffer extends javax.swing.JFrame
{
Buffer buffer;
Producer p;
Consumer c;
Topass paso = new Topass();
/**
* Creates new form BufferGrafico
*/
public DigitalBuffer() {
initComponents();
buffer = new Buffer(t1);
Producer A = new Producer("A",99,buffer);
Producer B = new Producer("B",99,buffer);
Producer C = new Producer("C",99,buffer);
Producer D = new Producer("D",99,buffer);
Consumer Luis = new Consumer("LUIS", buffer);
Consumer Juan = new Consumer("JUAN", buffer);
Consumer Maria = new Consumer("MARIA", buffer);
Consumer Ana = new Consumer ("ANA", buffer);
A.start();
B.start();
C.start();
D.start();
Luis.start();
Juan.start();
Maria.start();
Ana.start();
}
/**
* 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() {
t1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
JButton1 = new javax.swing.JButton();
JButton2 = new javax.swing.JButton();
JButton3 = new javax.swing.JButton();
JButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
t1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t1ActionPerformed(evt);
}
});
jLabel2.setText("Buffer content");
JButton1.setText("Stop Producers");
JButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton1ActionPerformed(evt);
}
});
JButton2.setText("Resume Producers");
JButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton2ActionPerformed(evt);
}
});
JButton3.setText("Stop Consumers");
JButton3.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
JButton3AncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
JButton3AncestorRemoved(evt);
}
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
});
JButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton3ActionPerformed(evt);
}
});
JButton4.setText("Resume Consumers");
JButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JButton4ActionPerformed(evt);
}
});
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(91, 91, 91)
.addComponent(JButton1)
.addGap(80, 80, 80)
.addComponent(JButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(102, 102, 102))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(104, 104, 104)
.addComponent(JButton3)
.addGap(77, 77, 77)
.addComponent(JButton4)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addComponent(jLabel1))
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton1)
.addComponent(JButton2))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JButton3)
.addComponent(JButton4))
.addContainerGap(64, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void t1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void JButton1ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.closed();
}
private void JButton2ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.open();
}
private void JButton3ActionPerformed(java.awt.event.ActionEvent evt) {
buffer.pass.closed();
}
private void JButton4ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void JButton3AncestorAdded(javax.swing.event.AncestorEvent evt) {
// TODO add your handling code here:
}
private void JButton3AncestorRemoved(javax.swing.event.AncestorEvent evt) {
// TODO add your handling code here:
}
/**
* #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(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DigitalBuffer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DigitalBuffer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton JButton1;
private javax.swing.JButton JButton2;
private javax.swing.JButton JButton3;
private javax.swing.JButton JButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField t1;
// End of variables declaration
}
The thing is that i don't know how to delete the messages when the Resume Consumers is pressed
You add an ActionListener to the button. In the ActionListener you reset the text. See the section from the Swing tutorial on How to Us Buttons for more information and examples. Or, there is also a section on How to Write an ActionListener.
You can replace the text in the text field by using:
textField.setText(...);
Example #1 (Requires Java 8+):
button.addActionListener(e -> textField.setText(""));
Example #2:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
In both cases, the textField will need to have been declared as final.

Why is my Java timer not working?

I am trying to make a simple Java GUI that allows you to enter a time, and once the time runs out, it plays a sound. For some reason I find an error despite looking a many different sources that all tell me to use Timer or Handler. Here is my code:
/*
* 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.
*/
/**
*
* #author CIS
*/
import java.io.*;
import sun.audio.*;
import java.util.TimerTask;
public class Timer extends javax.swing.JFrame {
public Timer() {
initComponents();
initEditable();
}
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop1 = null;
AudioPlayer ABC = AudioPlayer.player;
AudioStream ABCD;
AudioData ABCDE;
ContinuousAudioDataStream loop2 = null;
public void initEditable(){
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
textFieldTimer = new javax.swing.JTextField();
buttonTest = new javax.swing.JButton();
buttonSet = new javax.swing.JButton();
labelTimeRemaining = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonTest.setText("Test Sound");
buttonTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTestActionPerformed(evt);
}
});
buttonSet.setText("Set");
buttonSet.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSetActionPerformed(evt);
}
});
labelTimeRemaining.setText("time remaing");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(textFieldTimer)
.addComponent(buttonTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonSet)
.addComponent(labelTimeRemaining)))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonSet, buttonTest, labelTimeRemaining, textFieldTimer});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldTimer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTimeRemaining))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTest)
.addComponent(buttonSet)))
);
pack();
}// </editor-fold>
int hello = 1000;
public void music1(){
ContinuousAudioDataStream loop = null;
try
{
InputStream alert = new FileInputStream("alert.wav");
BGM = new AudioStream(alert);
AudioPlayer.player.start(BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD)
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop1);
}
private void buttonSetActionPerformed(java.awt.event.ActionEvent evt) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
music1();
}
}, 2000);
}
private void buttonTestActionPerformed(java.awt.event.ActionEvent evt) {
music1();
}
/**
* #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(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Timer.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 Timer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonSet;
private javax.swing.JButton buttonTest;
private javax.swing.JLabel labelTimeRemaining;
private javax.swing.JTextField textFieldTimer;
// End of variables declaration
}
When I get to the line new Timer().schedule(new TimerTask() {
I get on error on the schedule.
I apologize if my method of presenting my problem is incorrect, I'm new here and new to Java programming as well.
Your class has the same name as the java.util.Timer class. You must disambiguate by fully qualifying that class name:
new java.util.Timer().schedule(new TimerTask() {

Automatically traverse a dynamically created jPanels for component values

I have a program that creates a dynamic amount of jpanels and components based on selection at the start of the program that is user-defined. having said that each jpanel and component is created with a loop making them all the same, and they are then put into a list (the JPanel's are put into a list).
Having said that I have been able to get the jpanel out and then grab the componenets and display them using System.out. but they are in a component object. How can I get the values of the components? Or am I doing this wrong?
Basically I am trying to have the tabs/jpanels based on user-definition automatically generate, which works. Then the user fills out some information and hits "Generate" which is where I then need to iterate through the tabs/jpanels/componenents and put them into the correct object.
Below is a working example of my program in a simplified for, with less tyteps of tabs (I only let the AP tab be created) and less options for the object classes:
There are two object classes APObject is extending Generic Object. MVCE is the start of the main program where it asks you a few user-defined questions which generate the Tabs/Panels. It then goes from InfoGathering.java to DataGathering where it creates the tabs and panels. The GenerateActionPerformed(ActionEvent evt) method is where I am trying to grab the information from the panel components and put them into the APObject or whichever object they need to go into.
MVCE:
public class MVCE extends javax.swing.JFrame {
int numGenerate[];
private javax.swing.JComboBox cb;
/**
* Creates new form MVCE
*/
public MVCE() {
this.numGenerate = new int[3];
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() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jLabel1.setText("How many switches?");
jLabel2.setText("APS");
jButton1.setText("Create Button");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jButton1))
.addContainerGap(264, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
jLabel1.getAccessibleContext().setAccessibleName("How many switches");
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.setVisible(false);
InfoGathering Info = new InfoGathering(numGenerate);
}
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
cb = (javax.swing.JComboBox)evt.getSource();
String APNumber = (String)cb.getSelectedItem();
//System.out.println(APNumber + "AP Number");
numGenerate[1] = Integer.valueOf(APNumber);
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
cb = (javax.swing.JComboBox)evt.getSource();
String APNumber = (String)cb.getSelectedItem();
//System.out.println(APNumber + "AP Number");
numGenerate[0] = Integer.valueOf(APNumber);
}
/**
* #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(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MVCE.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 MVCE().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration
}
INFOGATHERING:
public class InfoGathering {
//public int infoVariables[];
public InfoGathering(int[] infoVars) {
startInfo(infoVars);
}
private void startInfo(int[] infoVars) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DataGathering(infoVars).setVisible(true);
}
});
}
//End of clss below
}
DATAGATHERING:
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* 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.
*/
/**
*
* #author kmalik
*/
public class DataGathering extends javax.swing.JFrame {
private int infoVariables[];
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel OuterPane;
//SwitchObject SWOb[] = new SwitchObject[30];
//APObject APOb[] = new APObject[30];
//ControllerObject CoOb[] = new ControllerObject[1];
//int devicesArrayCountSW = 0;
//int devicesArrayCountAP = 0;
//int devicesArrayCountCO = 0;
/**
* Creates new form DataGathering
* #param intVars
*/
public DataGathering(int[] intVars) {
infoVariables = Arrays.copyOf(intVars, intVars.length);
initComponents();
initDynamic();
}
/**
* 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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridLayout(1, 0));
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
private void initDynamic() {
OuterPane = new javax.swing.JPanel();
getContentPane().add(OuterPane);
OuterPane.add(jTabbedPane1);
JButton GenerateCode = new JButton("Generate Code");
OuterPane.setLayout(new BoxLayout(OuterPane, BoxLayout.Y_AXIS));
OuterPane.add(GenerateCode);
GenerateCode.addActionListener(new java.awt.event.ActionListener() {
private APObject Aobj;
private JPanel jobj;
private Component Components[];
private Component components;
public void actionPerformed(java.awt.event.ActionEvent evt) {
GenerateActionPerformed(evt);
}
private void GenerateActionPerformed(ActionEvent evt) {
//To change body of generated methods, choose Tools | Templates.
for(int i = 0; apList.size() > i; i++) {
//jobj = (JPanel) jList.get(i);
//System.out.println(jobj
Aobj = apList.get(i);
jobj = jList.get(i);
Components = jobj.getComponents();
System.out.println(Components + " Componenets of first panel");
for (int a=0; a < Components.length; a++) {
components = jobj.getComponent(a);
System.out.println(components);
if (Components[a] instanceof JComboBox) {
}
}
}
}
});
int SwitchCount = 1 , APCount = 1,CoCount = 1;
//String jp;
//need public# of switches, APs and controllers
for(int devicesCount =0;devicesCount < infoVariables.length;devicesCount++) {
if (devicesCount == 2 && infoVariables[devicesCount] == 1) {
createTab(CoCount, devicesCount);
}
for(int b=0; b < infoVariables[devicesCount]; b++) {
if (devicesCount == 0) {
//SWITCHES DYNAMICALLY CREATE
createTab(SwitchCount,devicesCount);
SwitchCount++;
} else if (devicesCount==1) {
//AP DYNAMICALLY CREATE
createTab(APCount,devicesCount);
APCount++;
} //end of full if loop
} //end of for loop
} // end of outer for loop
}
private javax.swing.JTabbedPane jTabbedPane1;
//ArrayList<SwitchObject> swList = new ArrayList<>();
ArrayList<APObject> apList = new ArrayList<>();
//ArrayList<ControllerObject> coList = new ArrayList<>();
ArrayList<JPanel> jList = new ArrayList<>();
private void createTab(int z,int y) {
if (y==0) {
//CREATE SWITCH TAB/PANEL
} else if (y==1) {
JPanel jp = new JPanel();
jTabbedPane1.addTab("AP_"+z,jp);
jp.setName("AP"+z);
APObject APOb = new APObject(jp.getName(), z);
apList.add(APOb);
jList.add(jp);
setLayout(new FlowLayout());
//Add Type of Device Checkbox
String[] apListName = {"APExample1","APExample2"};
JComboBox apListChkBox = new JComboBox(apListName);
jp.add(apListChkBox);
//Add NasID of Device with Label
JLabel apnasIDLabel = new JLabel("AP ID");
String apnasID;
JTextField apnasIDComboBox = new JTextField();
apnasIDComboBox.setColumns(9);
jp.add(apnasIDLabel);
jp.add(apnasIDComboBox);
//SNMP Location
JLabel apLocLabel = new JLabel("Location");
String apLoc;
JTextField apLocComboBox = new JTextField();
apLocComboBox.setColumns(9);
jp.add(apLocLabel);
jp.add(apLocComboBox);
jp.setBorder(BorderFactory.createLineBorder(Color.black));
this.pack();
} else if (y == 2) {
//CREATE CONTROLLER TAB/PANEL
}
}
}
APOBJECT:
public class APObject extends GenericObject {
private int channelScheme;
APObject(String x, int y) {
super(x,y);
}
//ip scheme box/subnet box get/set
//location get/set
//channel scheme get/set
private void setChannelScheme(int x) {
channelScheme = x;
}
private int getChannelScheme() {
return channelScheme;
}
}
GENERICOBJECT:
public class GenericObject {
private int telephone;
private String ipScheme;
private String Location;
public String DName;
public int getTelephone() {
return telephone;
}
protected void setTelephone(int x) {
telephone = x;
}
protected String getipScheme() {
return ipScheme;
}
protected void setipScheme(String x) {
ipScheme = x;
}
protected String getLocation() {
return Location;
}
protected void setLocation(String x) {
Location = x;
}
public GenericObject (String SName, int Tab) {
DName = SName;
int TabNum = Tab;
}
}

Close the JInternalFrame through JMenuItem

Hi i am creating internal frame, i want close internalframe through menu item but it closed the total frame. please help me.
Here is my code,
public class CloseWindow extends javax.swing.JFrame {
JTextArea tx;
int i=0;
public CloseWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Crete = new javax.swing.JMenuItem();
close = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Crete.setText("Create");
Crete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreteActionPerformed(evt);
}
});
jMenu1.add(Crete);
close.setText("Close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
jMenu1.add(close);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void CreteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreteActionPerformed
ActionEvent ae=evt;
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setSize(700, 700);
tx = new JTextArea();
internalFrame.add(tx);
tPane.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
tPane.remove(internalFrame);
}
});
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed
WindowEvent tabClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(tabClosingEvent);
}
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(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CloseWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CloseWindow.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 CloseWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem Crete;
private javax.swing.JMenuItem close;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tPane;
// End of variables declaration//GEN-END:variables
}
You are creating a new WindowEvent with
WindowEvent tabClosingEvent = new WindowEvent(this,....
and posting this to the event queue. The this here refers to the main frame. That's why it is closed.
However, you should usually not mess around with the event queue manually. Instead, you should do the respective actions programmatically with the method that perform the desired actions.
There are some parts of the code between the first { and the last } that might benefit from a slight cleanup, but in order to solve the actual issue, you could change your closeActionPerformed method to something like this:
private void closeActionPerformed(java.awt.event.ActionEvent evt)
{
Component c = tPane.getSelectedComponent();
if (c instanceof JInternalFrame)
{
JInternalFrame f = (JInternalFrame)c;
f.dispose();
tPane.remove(f);
}
}
(BTW: Then you also don't need the InternalFrameListener any more)

Trying to set config variables in MainWindow from ConfigWindow in Java and NetBeans

Right I have now recreated my problem follow SSCEE guidelines.
The following 3 classes (class code) should be ready for copy, pasting and compiling for you to see whats going wrong for me.
Menu(): (This is my main class)
public class Menu extends javax.swing.JFrame {
/**
* Creates new form Menu
*/
public Menu() {
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() {
cmdMainWindow = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
cmdMainWindow.setText("Main Window");
cmdMainWindow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdMainWindowActionPerformed(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()
.addContainerGap()
.addComponent(cmdMainWindow, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(cmdMainWindow)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmdMainWindowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MainWindow main = new MainWindow();
main.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(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.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 Menu().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmdMainWindow;
// End of variables declaration
}
MainWindow():
public class MainWindow extends javax.swing.JFrame {
private MainWindow main;
public String strOptionOne;
/**
* Creates new form MainWindow
*/
public MainWindow() {
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() {
lblOptionOne = new javax.swing.JLabel();
cmdOptions = new javax.swing.JButton();
txtOptionOne = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
cmdOptions.setText("Options");
cmdOptions.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdOptionsActionPerformed(evt);
}
});
txtOptionOne.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblOptionOne)
.addComponent(cmdOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtOptionOne))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblOptionOne)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtOptionOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addComponent(cmdOptions)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmdOptionsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ConfigWindow config = new ConfigWindow(main);
config.setVisible(true);
}
public String setOptionOne() {
ConfigWindow config = new ConfigWindow(main);
strOptionOne = config.getOptionOne();
return strOptionOne;
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton cmdOptions;
private javax.swing.JLabel lblOptionOne;
public javax.swing.JTextField txtOptionOne;
// End of variables declaration
}
ConfigWindow():
public class ConfigWindow extends javax.swing.JFrame {
private MainWindow main;
public String btnTxtOptionOne;
/**
* Creates new form ConfigWindow
*/
public ConfigWindow(MainWindow main) {
initComponents();
this.main = main;
}
public String getOptionOne() {
if ("1".equals(grpOptionOne.getSelection())) {
btnTxtOptionOne = "1";
return this.btnTxtOptionOne;
}
if ("2".equals(grpOptionOne.getSelection())) {
btnTxtOptionOne = "2";
return this.btnTxtOptionOne;
}
return btnTxtOptionOne;
}
/**
* 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() {
grpOptionOne = new javax.swing.ButtonGroup();
lblOptionOne = new javax.swing.JLabel();
btn1 = new javax.swing.JRadioButton();
btn2 = new javax.swing.JRadioButton();
cmdApplySettings = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
grpOptionOne.add(btn1);
btn1.setText("1");
grpOptionOne.add(btn2);
btn2.setText("2");
cmdApplySettings.setText("ApplySettings");
cmdApplySettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdApplySettingsActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblOptionOne)
.addGroup(layout.createSequentialGroup()
.addComponent(btn1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn2))
.addComponent(cmdApplySettings))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblOptionOne)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1)
.addComponent(btn2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmdApplySettings)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
main.txtOptionOne.setText(main.strOptionOne);
dispose();
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JRadioButton btn1;
private javax.swing.JRadioButton btn2;
private javax.swing.JButton cmdApplySettings;
private javax.swing.ButtonGroup grpOptionOne;
private javax.swing.JLabel lblOptionOne;
// End of variables declaration
}
So with all the code out the way, as I have just revised all of this I will mention what the issue is again.
When I go to ConfigWindow from MainWindow to select Options, after selecting options, a method in ConfigWindow gets the value of the selected button, and then a method in MainWindow gets this value, and sets it to a variable within MainWindow. Then on clicking Apply in ConfigWindow, the method from MainWindow should be run, setting the MainWindow variable with the option selected, however it doesnt!
I have trimmed trimmed trimmed my project to its most basic form, and now it throws an error in netbeans on clicking apply, whereas before it just didnt do anything at all, no error in netbeans.
I hope I've managed to fulfil SSCEE here ... I'm trying!!!
Here is the source, progressed over what you posted, compacted into a single source file. There are still problems to be fixed, but I put debug statements (printing out values) that should help to point out why it is still not working. See further notes at bottom of post.
public class Menu117 extends javax.swing.JFrame {
/**
* Creates new form Menu
*/
public Menu117() {
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() {
cmdMainWindow = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
cmdMainWindow.setText("Main Window");
cmdMainWindow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdMainWindowActionPerformed(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().addContainerGap().addComponent(cmdMainWindow, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE).addContainerGap()));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(cmdMainWindow).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void cmdMainWindowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MainWindow main = new MainWindow();
main.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(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu117.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 Menu117().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmdMainWindow;
// End of variables declaration
}
class MainWindow extends javax.swing.JFrame {
// This IS a MainWindow. No need to keep a reference to one as well!
//private MainWindow main;
public String strOptionOne;
/**
* Creates new form MainWindow
*/
public MainWindow() {
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() {
lblOptionOne = new javax.swing.JLabel();
cmdOptions = new javax.swing.JButton();
txtOptionOne = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
cmdOptions.setText("Options");
cmdOptions.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdOptionsActionPerformed(evt);
}
});
txtOptionOne.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(lblOptionOne).addComponent(cmdOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(txtOptionOne)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(txtOptionOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(11, 11, 11).addComponent(cmdOptions).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void cmdOptionsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ConfigWindow config = new ConfigWindow(this);
config.setVisible(true);
}
/*
* public String setOptionOne() { ConfigWindow config = new
* ConfigWindow(this);
*
* strOptionOne = config.getOptionOne(); return strOptionOne;
}
*/
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton cmdOptions;
private javax.swing.JLabel lblOptionOne;
public javax.swing.JTextField txtOptionOne;
// End of variables declaration
}
class ConfigWindow extends javax.swing.JFrame {
private MainWindow main;
public String btnTxtOptionOne;
/**
* Creates new form ConfigWindow
*/
public ConfigWindow(MainWindow main) {
initComponents();
this.main = main;
}
public String getOptionOne() {
System.out.println(grpOptionOne.getSelection().getActionCommand());
if ("1".equals(grpOptionOne.getSelection().getActionCommand())) {
btnTxtOptionOne = "1";
} else if ("2".equals(grpOptionOne.getSelection())) {
btnTxtOptionOne = "2";
} else {
btnTxtOptionOne = "-1";
}
return this.btnTxtOptionOne;
}
/**
* 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() {
grpOptionOne = new javax.swing.ButtonGroup();
lblOptionOne = new javax.swing.JLabel();
btn1 = new javax.swing.JRadioButton();
btn2 = new javax.swing.JRadioButton();
cmdApplySettings = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
grpOptionOne.add(btn1);
btn1.setText("1");
grpOptionOne.add(btn2);
btn2.setText("2");
cmdApplySettings.setText("ApplySettings");
cmdApplySettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdApplySettingsActionPerformed(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().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblOptionOne).addGroup(layout.createSequentialGroup().addComponent(btn1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(btn2)).addComponent(cmdApplySettings)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btn1).addComponent(btn2)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdApplySettings).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println(evt);
//main.txtOptionOne.setText(main.strOptionOne);
main.txtOptionOne.setText(getOptionOne());
dispose();
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JRadioButton btn1;
private javax.swing.JRadioButton btn2;
private javax.swing.JButton cmdApplySettings;
private javax.swing.ButtonGroup grpOptionOne;
private javax.swing.JLabel lblOptionOne;
// End of variables declaration
}
A single source file is needed for an SSCCE, but at 253 lines, it is not really 'short'. If you removed those (quite superfluous and irritating) auto-generated Netbeans comments and deleted the unnecessary code block to set a PLAF (which has nothing to do with this problem) it would probably be less than 150 lines of code, which is probably short enough to call 'an SSCCE'.
Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. In Netbeans, this is as easy as pressing the key combination Alt+Shift+F
That code seen above is how my current version of Netbeans formats the code, though I suspect that newer versions will leave out the first indent in order to have method signatures start at char 0 on a line (giving more width to display them).
I strongly suggest you put Netbeans aside for the moment. Until you are familiar with basic Java, it will just get in the way.
This source uses 3 frames. An application would (should) typically only have a single frame for the main application window. The other two might be put into a JDialog or a JOptionPane. See The Use of Multiple JFrames, Good/Bad Practice? for more details.
Got this sorted in the end, I was completely over thinking the issue.
Working Method:
public String getOptionOne() {
if (btn1.isSelected()) {
btnTxtOptionOne = "1";
} else if (btn2.isSelected()) {
btnTxtOptionOne = "2";
} else {
btnTxtOptionOne = "-1";
}
return this.btnTxtOptionOne;
}
Working Apply Button:
private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(evt);
main.txtOptionOne.setText(getOptionOne());
dispose();
}
Full SSCCCE Source:
public class Menu117 extends javax.swing.JFrame {
public Menu117() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
cmdMainWindow = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
cmdMainWindow.setText("Main Window");
cmdMainWindow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdMainWindowActionPerformed(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().addContainerGap().addComponent(cmdMainWindow, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE).addContainerGap()));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(cmdMainWindow).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
private void cmdMainWindowActionPerformed(java.awt.event.ActionEvent evt) {
MainWindow main = new MainWindow();
main.setVisible(true);
}
public static void main(String args[]) {
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(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Menu117().setVisible(true);
}
});
}
private javax.swing.JButton cmdMainWindow;
}
class MainWindow extends javax.swing.JFrame {
public String strOptionOne;
public MainWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
lblOptionOne = new javax.swing.JLabel();
cmdOptions = new javax.swing.JButton();
txtOptionOne = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
cmdOptions.setText("Options");
cmdOptions.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdOptionsActionPerformed(evt);
}
});
txtOptionOne.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(lblOptionOne).addComponent(cmdOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(txtOptionOne)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(txtOptionOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(11, 11, 11).addComponent(cmdOptions).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
private void cmdOptionsActionPerformed(java.awt.event.ActionEvent evt) {
ConfigWindow config = new ConfigWindow(this);
config.setVisible(true);
}
private javax.swing.JButton cmdOptions;
private javax.swing.JLabel lblOptionOne;
public javax.swing.JTextField txtOptionOne;
}
class ConfigWindow extends javax.swing.JFrame {
private MainWindow main;
public String btnTxtOptionOne;
public ConfigWindow(MainWindow main) {
initComponents();
this.main = main;
}
public String getOptionOne() {
if (btn1.isSelected()) {
btnTxtOptionOne = "1";
} else if (btn2.isSelected()) {
btnTxtOptionOne = "2";
} else {
btnTxtOptionOne = "-1";
}
return this.btnTxtOptionOne;
}
#SuppressWarnings("unchecked")
private void initComponents() {
grpOptionOne = new javax.swing.ButtonGroup();
lblOptionOne = new javax.swing.JLabel();
btn1 = new javax.swing.JRadioButton();
btn2 = new javax.swing.JRadioButton();
cmdApplySettings = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblOptionOne.setText("Option One");
grpOptionOne.add(btn1);
btn1.setText("1");
grpOptionOne.add(btn2);
btn2.setText("2");
cmdApplySettings.setText("ApplySettings");
cmdApplySettings.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdApplySettingsActionPerformed(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().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblOptionOne).addGroup(layout.createSequentialGroup().addComponent(btn1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(btn2)).addComponent(cmdApplySettings)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btn1).addComponent(btn2)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdApplySettings).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(evt);
main.txtOptionOne.setText(getOptionOne());
dispose();
}
private javax.swing.JRadioButton btn1;
private javax.swing.JRadioButton btn2;
private javax.swing.JButton cmdApplySettings;
private javax.swing.ButtonGroup grpOptionOne;
private javax.swing.JLabel lblOptionOne;
}
Just like to thank Andrew for all his help, his advice and assistance got me on the right path!

Categories