Close the JInternalFrame through JMenuItem - java

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)

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.

How do I show an icon on a JLabel when clicking on a JMenuItem?

I have put an icon in a JMenuItem. I want this icon to show on a JLabel when I click on the JMenuItem, how can I achieve that?
This 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.
*/
package labwork5;
/**
*
* #author haseeb shah
*/
public class lab5part2frame extends javax.swing.JFrame {
/**
* Creates new form lab5part2frame
*/
public lab5part2frame() {
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() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${icon}"), this, org.jdesktop.beansbinding.BeanProperty.create("iconImage"));
bindingGroup.addBinding(binding);
jLabel1.setIcon(jMenuItem1.getRolloverSelectedIcon());
jLabel1.setText("jLabel1");
jLabel1.setComponentPopupMenu(jMenuItem1.getComponentPopupMenu());
jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel1.addContainerListener(new java.awt.event.ContainerAdapter() {
public void componentRemoved(java.awt.event.ContainerEvent evt) {
jLabel1ComponentRemoved(evt);
}
});
jMenu1.setText("Mobile Networks");
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${icon}"), jMenu1, org.jdesktop.beansbinding.BeanProperty.create("actionCommand"));
bindingGroup.addBinding(binding);
jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenu1MouseClicked(evt);
}
});
jMenuItem1.setAction(java.swing.posticon(jLabel1));
jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/labwork5/province icon.jpg"))); // NOI18N
jMenuItem1.setText("Zain");
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${displayedMnemonic}"), jMenuItem1, org.jdesktop.beansbinding.BeanProperty.create("actionCommand"));
bindingGroup.addBinding(binding);
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Mobily");
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Gomo");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
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)
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(113, Short.MAX_VALUE))
);
bindingGroup.bind();
pack();
}// </editor-fold>
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jLabel1ComponentRemoved(java.awt.event.ContainerEvent evt) {
}
private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {
this.transferFocus();
}
/**
* #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(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.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 lab5part2frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration
}
Use the jlabel.setIcon(Icon icon) method.
Don't forget to use jlabel.revalidate() and jlabel.repaint() after update your GUI.

How to create on-screen keyboard like as windows by using java?

I want to write data in note pad by clicking that buttons.
By using using my code I tried to write in note pad it's not working. I want functionality like same as on-screen keyboard of windows. By windows on-screen keyboard we can write in note pad as well as in google chrome like that I want to create the application.
How can I create like that by using java ?
I tried below way but it's not working.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OnclickTest extends javax.swing.JFrame {
Robot robot;
public OnclickTest() throws AWTException {
initComponents();
robot = new Robot();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
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);
jButton1.setText("PAGE UP");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("PAGE DOWN");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("A");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("B");
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(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3)
.addComponent(jButton1))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton4))
.addContainerGap(141, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(168, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
robot.keyPress(KeyEvent.VK_PAGE_UP);
robot.keyRelease(KeyEvent.VK_PAGE_UP);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
robot.keyPress(KeyEvent.VK_B);
robot.keyRelease(KeyEvent.VK_B);
}
/**
* #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(OnclickTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OnclickTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OnclickTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OnclickTest.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() {
try {
new OnclickTest().setVisible(true);
} catch (AWTException ex) {
Logger.getLogger(OnclickTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// 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;
}

how to move jpanel at run time

I am working on an application and I want the jpanel to move around inside jframe at run time. here is the code I used
package testing;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ChangePanel extends javax.swing.JFrame {
public ChangePanel() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jPanel1MousePressed(evt);
}
});
jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel1MouseDragged(evt);
}
});
jLabel1.setText("panel to move");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jLabel1)
.addContainerGap(119, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel1)
.addContainerGap(81, Short.MAX_VALUE))
);
getContentPane().add(jPanel1);
jPanel1.setBounds(160, 60, 247, 161);
pack();
}// </editor-fold>
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
MouseAdapter ma = new MouseAdapter() {
int lastX =0, lastY =0;
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
// Move frame by the mouse delta
setLocation(getLocationOnScreen().x + x - lastX,
getLocationOnScreen().y + y - lastY);
lastX = x;
lastY = y;
}
};
}
private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {
MouseAdapter ma = new MouseAdapter() {
int lastX, lastY;
#Override
public void mousePressed(MouseEvent e) {
lastX = e.getXOnScreen();
lastY = e.getYOnScreen();
}};
}
/**
* #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(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChangePanel.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 ChangePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
but is not working
Some time ago, I've written a framework for such tasks. Maybe you find it useful (the library is Open Source):
Tutorial:
http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html
Javadoc:
http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/index.html
Info about the latest release:
http://puces-blog.blogspot.ch/2013/11/news-from-software-smithy-version-04.html
There's no need to put a MouseAdapter within an already defined Listener. In fact, you're simply declaring one and not using it in any way. Simply keep it inside the dragged event.
Like this. You can adapt it to the calculations you need to do.
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
jPanel1.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
}

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