Change jLable-text from another class - java

My problem: I can't change the text of a jLabel from an other class. In my JFrame-Class, which is called "NewJFrame" I have defined a method called "setLabelText()" in which the text of jLable1 is changed. This method is called from the main-Method, but the text doesn't change. What's wrong? would be very grateful for help!
public class Main {
static NewJFrame f = new NewJFrame();
public static void main(String[] args) {
f.main(null);
f.setLabelText("changedText");
}
}
and here my new JFrame class with a lot of generated stuff in there. The important thing is the setText()-Method.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
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(156, 156, 156)
.addComponent(jLabel1)
.addContainerGap(203, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(152, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(132, 132, 132))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
//<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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
public void setLabelText (String text){
jLabel1.setText(text);
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}

I need to call the setText()-method from Main-class
What is the purpose of f.main(null); and you are trying to set text to the JFrame in this line: f.setText("changedText");
As a solution, change your JLabel access modifier to public. By default it is private, because of that you cannot change it in another class.
Change:
private javax.swing.JLabel jLabel1;
To:
public javax.swing.JLabel jLabel1;
In netbenas you cannot edit generated codes by default. So to change access modifier, right click on the JLabel in design window* and go to the customize code. In that window change the Access: to public.
Now, change the Main class as below:
public class Main {
static NewJFrame f = new NewJFrame();
public static void main(String[] args) {
f.jLabel1.setText("changedText");//this line will get the label in NewJFrame and set the text
//f.setVisible(true);//this is added to open the frame. May be you dont want this line
}
}

When you create JFrame frame (from netbeans) it already have its main function in it. so either you have to create JPanel and manually initialize in your class having main function, or you can move f.setText("XYZ"); to the NewJFrame() class.
It would be like :
public static void main(String args[]) {
//<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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
***NewJFrame f=new NewJFrame();
f.setVisible(true);
f.setText("Your Text Goes Here");***
}
});
}

Related

Why this actionEvent on a Java Swing menu item does not work?

I have created a basic JFrame using NetBeans form designer. I have reduced it to just a couple of menu items.
I intend to do something when user clicks on "Open", my understanding is that I have to add an "actionPerformed" through a listener, which can be done using NetBeans Designer.
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
But when I click on "Open" nothing happens I can not see the output message.
This is my main routine:
package test.dbviewer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SealionDBViewer {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
JFrame databaseViewer = new DatabaseViewer();
databaseViewer.setVisible(true);
}
}
This is the reproducible code that NetBeans generate:
package test.dbviewer;
public class DatabaseViewer extends javax.swing.JFrame {
/**
* Creates new form DatabaseViewer
*/
public DatabaseViewer() {
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() {
jSplitPane1 = new javax.swing.JSplitPane();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
jMenuItem1.setText("jMenuItem1");
jMenuItem2.setText("jMenuItem2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu3.setText("Open");
jMenu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu3ActionPerformed(evt);
}
});
jMenuBar2.add(jMenu3);
jMenu4.setText("Exit");
jMenuBar2.add(jMenu4);
setJMenuBar(jMenuBar2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 267, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
/**
* #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(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.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 DatabaseViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JSplitPane jSplitPane1;
// End of variables declaration
}

I can't initialize my array of objects outside of my event method

I want to make a program that will create a Array of objects that will store the number of times a user has clicked a button.
I ask the user what their id number is and then access their element of the array and update their button clicks.
The problem is that it won't let me set
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors(); unless I put the code in my attemptUpdateActionPerformed method, but I need to set it up outside of the method so it will not reset itself each time the button is clicked. There is a lot of extra stuff in here, but I think the main problem lies in the method. Sorry for the sloppiness.
package guildquality;
import java.util.Scanner;
public class NewJFrame extends javax.swing.JFrame {
Surveyors [] surveyor = new Surveyors[10];
Scanner scan = new Scanner(System.in);
public int id;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors();
id = 0;
}
/**
* 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() {
attemptUpdate = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
attemptUpdate.setText("Attempt");
attemptUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
attemptUpdateActionPerformed(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(21, 21, 21)
.addComponent(attemptUpdate)
.addContainerGap(308, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(173, Short.MAX_VALUE)
.addComponent(attemptUpdate)
.addGap(104, 104, 104))
);
pack();
}// </editor-fold>
private void attemptUpdateActionPerformed(java.awt.event.ActionEvent evt) {
System.out.print("what is your id?");
id = scan.nextInt();
surveyor[id].setAttempts();
System.out.print(surveyor[id].getAttempts());
// 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton attemptUpdate;
// End of variables declaration
}
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
at guildquality.NewJFrame.<init>(NewJFrame.java:19)
at guildquality.Surveyors.<init>(Surveyors.java:17)
at guildquality.NewJFrame.<init>(NewJFrame.java:20)
Put it in the main method. It will run once and before the eventhandler can run.
You should put code you want to initialize non-static class variable once in the constructor.
eg.
public NewJFrame() {
initComponents();
// More initialization here.
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors();
}

Why does closing sub-frame close also the main frame in Java swing..?

I created a simple frame, call it F1 which contains only a button which on pressing opens a new frame, call it F2. Now when I close F2, even F1 is getting closed along with F2. How do I overcome this.?
When I close F2 only F2 should be closed as it is a sub-frame and when I close F1 both F1 and F2 should be closed as F1 is the Main Frame
Here is the code for Main frame(F1)
package swingex;
public class NewJFrame1 extends javax.swing.JFrame {
public NewJFrame1() {
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() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addComponent(jButton1)
.addContainerGap(189, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(jButton1)
.addContainerGap(149, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new NewJFrame2().setVisible(true);
// 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(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame1.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 NewJFrame1().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
}
and the code for the sub frame is..
package swingex;
public class NewJFrame2 extends javax.swing.JFrame {
public NewJFrame2() {
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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, 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(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.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 NewJFrame2().setVisible(true);
}
});
}
Though I didn't write the code..it was made using NetBeans..
Thank You..
In your "sub frame" change the default close operation to: DISPOSE_ON_CLOSE
Don't use a JFrame. An application should only have a single JFrame. See The Use of Multiple JFrames: Good or Bad Practice?
Child windows would then generally be a JDialog. The default close operation for a JDialog is DISPOSE_ON_CLOSE (or HIDE_ON_CLOSE). Either way you don't have this problem.

How do I pass data between cards in Java CardLayout

I am new to working with Java GUI, I know this may sound ridiculous but I have been trying for days to pass data between cards on the CardLayout layout. I am using netbeans, the first card displays a list clients. When a client is selected, the choice selection is passed to a variable on that card. The next card queries the database to show more details about the client selected. I can handle the switching between cards but my problem is I can't pass the data stored in the variable on card 1 to card 2.
I have visited several forums and read through similar questions asked but I just cannot get any of the proposed solutions to work. Please help, I'm new at this so please go easy on me, thanks.
Here is the class that holds the panels
public class mainframe extends javax.swing.JFrame {
public mainframe() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
displayScrollPane = new javax.swing.JScrollPane();
displaypanel = new javax.swing.JPanel();
viewclientspanel1 = new viewclientspanel();
addclientpanel1 = new addclientpanel();
clientdetails1 = new clientdetails();
mainmenu = new javax.swing.JMenuBar();
clients = new javax.swing.JMenu();
viewclients = new javax.swing.JMenuItem();
addclient = new javax.swing.JMenuItem();
transactions = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
displaypanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
displaypanel.setLayout(new java.awt.CardLayout());
viewclientspanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
viewclientspanel1MouseClicked(evt);
}
});
displaypanel.add(viewclientspanel1, "viewclientscard");
displaypanel.add(addclientpanel1, "addclientcard");
displaypanel.add(clientdetails1, "clientdetailscard");
displayScrollPane.setViewportView(displaypanel);
clients.setText("Clients");
viewclients.setText("View Clients");
viewclients.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewclientsActionPerformed(evt);
}
});
clients.add(viewclients);
viewclients.getAccessibleContext().setAccessibleParent(mainmenu);
addclient.setText("Add Client");
addclient.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addclientActionPerformed(evt);
}
});
clients.add(addclient);
mainmenu.add(clients);
transactions.setText("Transactions");
mainmenu.add(transactions);
setJMenuBar(mainmenu);
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(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 1059, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>
private void addclientActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "addclientcard");
}
private void viewclientsActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "viewclientscard");
}
private void viewclientspanel1MouseClicked(java.awt.event.MouseEvent evt) {
//viewclientspanel1.getComponentListeners();
}
/**
* #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(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainframe.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 mainframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem addclient;
private addclientpanel addclientpanel1;
private clientdetails clientdetails1;
private javax.swing.JMenu clients;
private javax.swing.JScrollPane displayScrollPane;
private javax.swing.JPanel displaypanel;
private javax.swing.JMenuBar mainmenu;
private javax.swing.JMenu transactions;
private javax.swing.JMenuItem viewclients;
private viewclientspanel viewclientspanel1;
// End of variables declaration
}
The class of the card that displays a list of the clients to choose from has a mouse event listener which gets the value of the client selected and switches the the next card
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
CardLayout card = (CardLayout) jPanel1.getParent().getParent().getParent().getParent().getLayout();
card.show(jPanel1.getParent().getParent().getParent().getParent(), "clientdetailscard");
}
Lastly the class that I need to transfer the client selected information to which dsiplays the more details.
public class clientdetails extends javax.swing.JPanel {
public clientdetails() {
initComponents();
}
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(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
JFrame f = new JFrame("Window");
f.add(new clientdetails());
f.setSize(500, 700);
f.setVisible(true);
}
private javax.swing.JPanel jPanel1;
}
You could pass the client information from one pane to the other using setters/getters...
clientDetailsPane.setClient(clientListPanel.getClient());
// Switch panels...
I was also thinking that you could use some kind of model or Map, but that is probably overkill for what you want to achieve...
Thanks a lot guys, I ended up using a class container to hold the variables I need transferred.
public class varcontainer {
public String variablename;
private static varcontainer instance = null;
public static varcontainer getInstance(){
if(instance == null){
instance = new varcontainer();
}
return instance;
}
}
I then call the getInstance from another class to get the current instance of the container and access the variables
varcontainer.getInstance().variablename
Thanks again for the feedback, I appreciate it.

Setting Text in jTextField in netbeans

I know how to set text using JtextField in java. But for some weird reason. I am not able to manipulate the jtextfield in netbeans.
What I want is to manipulate the text from main(), the user will enter the string and that string should be shown in jTextField.
Here is the code:
import javax.swing.JOptionPane;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Sachin
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
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() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
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(134, 134, 134)
.addComponent(jButton1)
.addContainerGap(193, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jButton1)
.addContainerGap(224, 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
String inputValue = JOptionPane.showInputDialog("Please any enter any String");
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
You can do the following plumbing to store inputValue in the NewJFrame object.
private String input;
public NewJFrame(String input) {
this.input = input;
initComponents();
}
new NewJFrame(inputValue);
Then in the NetBeansIDE you can in the GUI editor set the custom creation code of the JTextField to new JTextField(input) or simply call setText.

Categories