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.
Related
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
}
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");***
}
});
}
so, my first post.
I study Java. There I got an issue. I want to get a pop.up window open, when attempting to close a window 0 frame.
So, I insert this. From an example code of the teacher.
Check it out please
here it goes
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int reply = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
this.dispose();
if (reply == JOptionPane.NO_OPTION)
this.setVisible(true);
}
}
It does nothing. no pop up window that gives me what is demanded
Your method most likely won't ever be called. You need to use a WindowListener. Here is how you set it up:
JFrame mainFrame = new JFrame(); //that's your frame
mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) //enable windowlistener handling
mainFrame.addWindowListener(new WindowListener() { //you need to add a windowlistener
#Override
public void windowClosing(WindowEvent e) {
formWindowClosing(e); //call your method
}
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
});
This will call your closing method when your program requests to exit.
I use the NetBeans platform.
So my code is as follows:
package my.exercise21;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class Exercise21 extends javax.swing.JFrame {
/**
* Creates new form Exercise21
*/
public Exercise21() {
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() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Exit");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
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)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
// TODO add your handling code here:
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int reply = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
this.dispose();
if (reply == JOptionPane.NO_OPTION)
this.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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Exercise21.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Exercise21().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
I guess my problem lies in not calling the JOptionPane library
I have had just fixed the issue. Thank you for helpful participation and your kind inspiration.
/*
* 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 my.exercise21;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
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() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Exercise 2.1");
setCursor(new java.awt.Cursor(java.awt.Cursor.NW_RESIZE_CURSOR));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Exit");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
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)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void formWindowClosed(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int r = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (r == JOptionPane.YES_OPTION) {
dispose(); // This closes the program
if (r == JOptionPane.YES_OPTION)
setVisible(false); // This just hides the window but program keeps running.
}// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
dispose(); // 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.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
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();
}
I am building an application with a Swing GUI. If you would would open this program from the command line, Some text will print (info and error messages). The program is just a normal executable jar file, but for the people who want to see a console I want an option to open a console from the Swing GUI, which displays all these messages, outputted by System.out.print(). I have seen several applications which have such a function, but I don't know how to do this.
The basics are explained at https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and. That example uses logging to redirect stdout and stderr. A simple approach could be to first define an OutputStream that writes to the "console":
package outerr;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JTextArea;
public class PrintOutErrStream extends ByteArrayOutputStream {
final int maxTextAreaSize = 1000;
private JTextArea textArea;
public PrintOutErrStream(JTextArea textArea) {
this.textArea = textArea;
}
public void flush() throws IOException {
synchronized(this) {
super.flush();
String outputStr = this.toString();
super.reset();
if(textArea.getText().length() > maxTextAreaSize) {
textArea.replaceRange("", 0, 100);
}
textArea.append(outputStr);
}
}
}
Then this is the remaining part of a demo program:
package outerr;
import java.io.PrintStream;
public class StdOutErr extends javax.swing.JFrame {
/** Creates new form StdOutErr */
public StdOutErr() {
initComponents();
PrintOutErrStream poes = new PrintOutErrStream(this.jTextAreaOutErrLog);
System.setErr(new PrintStream(poes, true));
System.setOut(new PrintStream(poes, true));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this
* method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jButtonStdout = new javax.swing.JButton();
jButtonStderr = new javax.swing.JButton();
jPanelOutErrLog = new javax.swing.JPanel();
jScrollPaneOutErrLog = new javax.swing.JScrollPane();
jTextAreaOutErrLog = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jButtonStdout.setText("stdout");
jButtonStdout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStdoutActionPerformed(evt);
}
});
getContentPane().add(jButtonStdout);
jButtonStderr.setText("stderr");
jButtonStderr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStderrActionPerformed(evt);
}
});
getContentPane().add(jButtonStderr);
jTextAreaOutErrLog.setColumns(20);
jTextAreaOutErrLog.setRows(5);
jScrollPaneOutErrLog.setViewportView(jTextAreaOutErrLog);
javax.swing.GroupLayout jPanelOutErrLogLayout = new javax.swing.GroupLayout(jPanelOutErrLog);
jPanelOutErrLog.setLayout(jPanelOutErrLogLayout);
jPanelOutErrLogLayout.setHorizontalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 835, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 835, Short.MAX_VALUE))
);
jPanelOutErrLogLayout.setVerticalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 378, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE))
);
getContentPane().add(jPanelOutErrLog);
pack();
}// </editor-fold>
private void jButtonStdoutActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("message via stdout");
}
private void jButtonStderrActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("message via stderr");
}
/**
* #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(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StdOutErr.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 StdOutErr().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonStderr;
private javax.swing.JButton jButtonStdout;
private javax.swing.JPanel jPanelOutErrLog;
private javax.swing.JScrollPane jScrollPaneOutErrLog;
private javax.swing.JTextArea jTextAreaOutErrLog;
// End of variables declaration
}