Automatically traverse a dynamically created jPanels for component values - java

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;
}
}

Related

Java Swing Label not updating when called from outside class

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.

Conversion to OOP [duplicate]

This question already has answers here:
error: incompatible types: unexpected return value Char compare to String
(3 answers)
Void methods cannot return a value
(10 answers)
Closed 3 years ago.
I am trying to convert a clock in and clock out program given by my lecturer at my universtiy to OOP. This is the original source code.
package gui;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JAVASwingForm {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JAVASwingForm window = new JAVASwingForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JAVASwingForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 730, 489);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(228, 28, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblName = new JLabel("Clock In");
lblName.setBounds(65, 31, 100, 14);
frame.getContentPane().add(lblName);
JLabel lblPhone = new JLabel("Clock Out");
lblPhone.setBounds(65, 68, 100, 14);
frame.getContentPane().add(lblPhone);
textField_1 = new JTextField();
textField_1.setBounds(228, 65, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnSubmit = new JButton("Calculate");
btnSubmit.setBounds(65, 200, 89, 23);
frame.getContentPane().add(btnSubmit);
JLabel timeResult = new JLabel("Time Difference will show here");
timeResult.setBounds(65, 115, 200, 14);
frame.getContentPane().add(timeResult);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (textField.getText().isEmpty() || textField_1.getText().isEmpty())
JOptionPane.showMessageDialog(null, "Data Missing");
else {
//Nicholas - implementation and customization starts from here
String time1 = textField.getText();
String time2 = textField_1.getText();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(time1);
date2 = format.parse(time2);
} catch (ParseException e) {
// TODO Auto-generated catch block
timeResult.setText(e.toString());
}
// Nicholas - Substraction from here in miliseconds
long diff = date2.getTime() - date1.getTime();
// Nicholas - convert milisecond to hours and minutes
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
timeResult.setText(diffHours + " hours, and " + diffMinutes + " Minutes");
}
}
});
}
}
And this is my conversion so far.
package gui.form;
public class Backend implements Clock {
public double timelength;
private double TimeIn , TimeOut;
private double calcTime;
public double timelength(){
return calcTime;
}
public Backend(){
}
public double calcTime(){
return( TimeIn - TimeOut);
}
public double getTimelength() {
return timelength;
}
public void setTimelength(double timelength) {
this.timelength = timelength;
}
public double getTimeIn() {
return TimeIn;
}
public void setTimeIn(double TimeIn) {
this.TimeIn = TimeIn;
}
public double getTimeOut() {
return TimeOut;
}
public void setTimeOut(double TimeOut) {
this.TimeOut = TimeOut;
}
#Override
public double setTime() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public double calcTime(double timelength) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
package gui.form;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Form {
private double timelength;
private double TimeIn , TimeOut;
/**
* Creates new form Form
*/
public Form() {
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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
TItxt = new javax.swing.JTextField();
TOtxt = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
LTimetxt = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Time In");
jLabel2.setText("Time Out");
TItxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
TItxtActionPerformed(evt);
}
});
jButton1.setText("Enter");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Length of Time");
LTimetxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LTimetxtActionPerformed(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()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(29, 29, 29))
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addComponent(jLabel3))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(TOtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
.addComponent(TItxt)
.addComponent(LTimetxt))
.addContainerGap(166, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(TItxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(TOtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(LTimetxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(21, 21, 21))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
{
TItxt.getText();
TOtxt.getText();
}
return LTimetxt.setText();
// TODO add your handling code here:
}
private void TItxtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void LTimetxtActionPerformed(java.awt.event.ActionEvent 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(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Form.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 Form().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField LTimetxt;
private javax.swing.JTextField TItxt;
private javax.swing.JTextField TOtxt;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration
public double getTimelength() {
return (TimeIn - TimeOut);
}
public void setTimelength(double timelength) {
this.timelength = (TimeIn - TimeOut);
}
public double getTimeIn() {
return TimeIn;
}
public void setTimeIn(double TimeIn) {
this.TItxt = TItxt;
}
public double getTimeOut() {
return TimeOut;
}
public void setTimeOut(double TimeOut) {
this.TOtxt = TOtxt;
}
public JTextField getTItxt() {
return TItxt;
}
public void setTItxt(JTextField TItxt) {
this.TItxt = TItxt;
}
public JTextField getTOtxt() {
return TOtxt;
}
public void setTOtxt(JTextField TOtxt) {
this.TOtxt = TOtxt;
}
public JButton getjButton1() {
return jButton1;
}
public void setjButton1(JButton jButton1) {
this.jButton1 = jButton1;
}
public JLabel getjLabel1() {
return jLabel1;
}
public void setjLabel1(JLabel jLabel1) {
this.jLabel1 = jLabel1;
}
public JLabel getjLabel2() {
return jLabel2;
}
public void setjLabel2(JLabel jLabel2) {
this.jLabel2 = jLabel2;
}
public JTextField getLTimetxt() {
return LTimetxt;
}
public int setLTimetxt(JTextField LTimetxt) {
this.LTimetxt = LTimetxt;
return (int) (TimeIn - TimeOut);
}
private void setVisible(boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
package gui.form;
public interface Clock {// template of the class
public double setTime(); //method to be implemented at the sub class
public double calcTime(double timelength); //method to be implemented at the sub class
}
package gui.form;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class JAVASwingForm {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
Backend backend = new Backend();
Form form = new Form();
}
}
I have set up 2 classes, a main class and a interface, however, I cant seem to get it to work and always seem to hit an error. enter image description here
Your Problem as seen in your Image is that you return a value in a void method.

Call variable from other java class

I have this loginscreen class;
/*
* 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 program;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
* #author Lacrymae_Ev
*/
public class loginscreen extends javax.swing.JFrame {
public String username;
public String getUsername() {
return username;
}
private String pwd;
public String getPassword() {
return pwd;
}
/**
* Creates new form loginscreen
*/
public loginscreen() {
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() {
Uname_Textfield = new javax.swing.JTextField();
Password_PasswordField = new javax.swing.JPasswordField();
Buton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
Buton.setText("Bağlan");
Buton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButonActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(Buton)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Buton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void ButonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String username=Uname_Textfield.getText();
String pwd= new String (Password_PasswordField.getPassword());
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + username + ";" + "password=" + pwd + ";";
Connection con = DriverManager.getConnection(connectionUrl);
new ProgramPenceresi().setVisible(true);
dispose();
}
catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Wrong username or passwordş!");
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
/**
* #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(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(loginscreen.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 loginscreen().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton Buton;
private javax.swing.JPasswordField Password_PasswordField;
private javax.swing.JTextField Uname_Textfield;
// End of variables declaration
}
And i have other class;
/*
* 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 program;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
/**
*
* #author Lacrymae_Ev
*/
public class cagbas extends javax.swing.JFrame {
loginscreen logindetails = new loginscreen ();
String uname = logindetails.getUsername();
String pass = logindetails.getPassword();
private static ResultSet rs;
private static Statement stmt;
private static Connection con;
private static final String query = "select 'AICB',sum(dur) as dur,sum(tot)as tot from exampletable with(nolock)\n" +
"where date between '2013-07-01 00:00:00.000' and '2013-07-01 23:59:59.999'\n" +
"and id='013'";
/**
* Creates new form cagbas
*/
public cagbas() {
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();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jScrollPane1.setViewportView(jTable1);
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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, 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(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + uname + ";" + "password=" + pass + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new cagbas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
But i have problem in cagbas.java because when i start this class java return below error;
I understand i cant use non-static obj in main method. But how i can use first user entered true username and password in my program ?
One problem I see is that your LoginScreen class is a JFrame, and a JFrame's behavior is to not stop program flow from the calling code when it is displayed, so even if you could extract the login name and password from this object in your later code, you'll be extracting it too early, before the user has had a time to enter anything.
Suggestions:
Most important is that you're trying to run code that won't compile. Never do this as this is guaranteed to always fail. Instead, fix compilation issues before trying to run your program.
Your LoginScreen should be a modal JDialog and not a JFrame.
You first display this window in order to get the user's input.
Key point here is, that because it is a modal JDialog, the calling code flow stops when the dialog is displayed.
The calling code then resumes once the dialog has been dealt with and is no longer visible, meaning once the user has either entered data or canceled the dialog.
At that time, you then get the login user's name and password (best if the latter is obtained as a char[]) from the LoginScreen instance by calling getter methods, and checking to be sure that they are not null. i.e., LoginScreen should have a public String getUserName() method and a public char[] getPassword() method.
The calling code can now use this information in the database.
And yeah, please learn Java naming conventions, and please comply with them by having your class names start with upper-case letters and method and variable names with lower-case letters. This will make it easier for folks trying to understand your code and help you, namely the volunteers here, do it better.
Edit
Note also that a JOptionPane is really nothing more than a modal JDialog, and this can be used for your purposes as well, and easily too. For example, in the example code below I create an InputForm JPanel and then place that JPanel into the JOptionPane:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainFoo extends JPanel {
private static final int COLUMNS = 10;
private JTextField userNameField = new JTextField(COLUMNS);
private JTextField passwordField = new JTextField(COLUMNS);
private InputForm inputForm = new InputForm();
public MainFoo() {
add(new JLabel("User Name:"));
add(userNameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Password:"));
add(passwordField);
add(new JButton(new LogInAction("Log in", KeyEvent.VK_L)));
}
private class LogInAction extends AbstractAction {
public LogInAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
userNameField.setText(inputForm.getUserName());
// ***** never do this! *****
// Never change a password into a String.
// This is for demo purposes only.
passwordField.setText(new String(inputForm.getPassword()));
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MainFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainFoo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private JTextField userNameField = new JTextField(COLUMNS);
private JPasswordField passwordField = new JPasswordField(COLUMNS);
public InputForm() {
setLayout(new GridBagLayout());
addLabel("User Name:", 0);
addTextField(userNameField, 0);
addLabel("Password:", 1);
addTextField(passwordField, 1);
}
public String getUserName() {
return userNameField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
}
Is it really your goal to have the loginscreen be global to all instances of your cagbas classes? I'm guessing you want to define loginscreen logindetails as class variables but you want to instantiate them during cagbas class creation/initialization.
Something like this:
public class cagbas extends javax.swing.JFrame {
loginscreen logindetails;
String uname;
String pass;
....
public cagbas () {
initComponents();
logindetails = new loginscreen ();
uname = logindetails.getUsername();
pass = logindetails.getPassword();
One style note, capitalize your classnames.
[edit]
You can't access uname in main because main is static and uname is not. Move that assignation into a function AFTER you instantiate your Cagbas class.
[/edit]

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!

How to wire one pane to another

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.

Categories