Call variable from other java class - java

I have this loginscreen class;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package program;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
* #author Lacrymae_Ev
*/
public class loginscreen extends javax.swing.JFrame {
public String username;
public String getUsername() {
return username;
}
private String pwd;
public String getPassword() {
return pwd;
}
/**
* Creates new form loginscreen
*/
public loginscreen() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
Uname_Textfield = new javax.swing.JTextField();
Password_PasswordField = new javax.swing.JPasswordField();
Buton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
Buton.setText("Bağlan");
Buton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(Buton)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Buton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void ButonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String username=Uname_Textfield.getText();
String pwd= new String (Password_PasswordField.getPassword());
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + username + ";" + "password=" + pwd + ";";
Connection con = DriverManager.getConnection(connectionUrl);
new ProgramPenceresi().setVisible(true);
dispose();
}
catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Wrong username or passwordş!");
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(loginscreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new loginscreen().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton Buton;
private javax.swing.JPasswordField Password_PasswordField;
private javax.swing.JTextField Uname_Textfield;
// End of variables declaration
}
And i have other class;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package program;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
/**
*
* #author Lacrymae_Ev
*/
public class cagbas extends javax.swing.JFrame {
loginscreen logindetails = new loginscreen ();
String uname = logindetails.getUsername();
String pass = logindetails.getPassword();
private static ResultSet rs;
private static Statement stmt;
private static Connection con;
private static final String query = "select 'AICB',sum(dur) as dur,sum(tot)as tot from exampletable with(nolock)\n" +
"where date between '2013-07-01 00:00:00.000' and '2013-07-01 23:59:59.999'\n" +
"and id='013'";
/**
* Creates new form cagbas
*/
public cagbas() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(cagbas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + uname + ";" + "password=" + pass + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new cagbas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
But i have problem in cagbas.java because when i start this class java return below error;
I understand i cant use non-static obj in main method. But how i can use first user entered true username and password in my program ?

One problem I see is that your LoginScreen class is a JFrame, and a JFrame's behavior is to not stop program flow from the calling code when it is displayed, so even if you could extract the login name and password from this object in your later code, you'll be extracting it too early, before the user has had a time to enter anything.
Suggestions:
Most important is that you're trying to run code that won't compile. Never do this as this is guaranteed to always fail. Instead, fix compilation issues before trying to run your program.
Your LoginScreen should be a modal JDialog and not a JFrame.
You first display this window in order to get the user's input.
Key point here is, that because it is a modal JDialog, the calling code flow stops when the dialog is displayed.
The calling code then resumes once the dialog has been dealt with and is no longer visible, meaning once the user has either entered data or canceled the dialog.
At that time, you then get the login user's name and password (best if the latter is obtained as a char[]) from the LoginScreen instance by calling getter methods, and checking to be sure that they are not null. i.e., LoginScreen should have a public String getUserName() method and a public char[] getPassword() method.
The calling code can now use this information in the database.
And yeah, please learn Java naming conventions, and please comply with them by having your class names start with upper-case letters and method and variable names with lower-case letters. This will make it easier for folks trying to understand your code and help you, namely the volunteers here, do it better.
Edit
Note also that a JOptionPane is really nothing more than a modal JDialog, and this can be used for your purposes as well, and easily too. For example, in the example code below I create an InputForm JPanel and then place that JPanel into the JOptionPane:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainFoo extends JPanel {
private static final int COLUMNS = 10;
private JTextField userNameField = new JTextField(COLUMNS);
private JTextField passwordField = new JTextField(COLUMNS);
private InputForm inputForm = new InputForm();
public MainFoo() {
add(new JLabel("User Name:"));
add(userNameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Password:"));
add(passwordField);
add(new JButton(new LogInAction("Log in", KeyEvent.VK_L)));
}
private class LogInAction extends AbstractAction {
public LogInAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
userNameField.setText(inputForm.getUserName());
// ***** never do this! *****
// Never change a password into a String.
// This is for demo purposes only.
passwordField.setText(new String(inputForm.getPassword()));
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MainFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainFoo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private JTextField userNameField = new JTextField(COLUMNS);
private JPasswordField passwordField = new JPasswordField(COLUMNS);
public InputForm() {
setLayout(new GridBagLayout());
addLabel("User Name:", 0);
addTextField(userNameField, 0);
addLabel("Password:", 1);
addTextField(passwordField, 1);
}
public String getUserName() {
return userNameField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
}

Is it really your goal to have the loginscreen be global to all instances of your cagbas classes? I'm guessing you want to define loginscreen logindetails as class variables but you want to instantiate them during cagbas class creation/initialization.
Something like this:
public class cagbas extends javax.swing.JFrame {
loginscreen logindetails;
String uname;
String pass;
....
public cagbas () {
initComponents();
logindetails = new loginscreen ();
uname = logindetails.getUsername();
pass = logindetails.getPassword();
One style note, capitalize your classnames.
[edit]
You can't access uname in main because main is static and uname is not. Move that assignation into a function AFTER you instantiate your Cagbas class.
[/edit]

Related

Created a passwordfield in java that is supposed to log in and allow you to move to second Jframe, it doesnt work?

I'm trying to do a log in I've gotten the username to work but the password is failing hard, I've tried multiple techniques and different ways and all of them have failed, my last effort seems to do nothing at all no error messages either where my previous stuff displayed error.
Can you please help me fix this + show me how to navigate to another page if the access is verified and password and username is right?
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Arrays;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MainMenu extends javax.swing.JFrame {
private JLabel username;
private JLabel passwordlbl;
private JLabel Welco;
private JPasswordField Passwordfld;
private JButton Cancelbtn;
private JButton OKbtn;
private JTextField Usernametxt;
private String Password = "pass";
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
//PASSWORD field to store new password inside
//Passwordfld.setEchoChar('*');
//Passwordfld.addActionListener(new AL());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainMenu inst = new MainMenu();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public MainMenu() {
super();
initGUI();
}
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
username = new JLabel();
getContentPane().add(username);
username.setText("User Name:");
username.setBounds(63, 113, 80, 16);
passwordlbl = new JLabel();
getContentPane().add(passwordlbl);
passwordlbl.setText("Password:");
passwordlbl.setBounds(63, 160, 72, 16);
Usernametxt = new JTextField();
getContentPane().add(Usernametxt);
Usernametxt.setBounds(198, 110, 79, 23);
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(Usernametxt.getText().equals("Admin")){} /*&&
(Passwordfld.getText().equals("Admin2"))*/
String cmd = evt.getActionCommand();
if (OKbtn.equals(cmd)) { //Process the password.
char[] input = Passwordfld.getPassword();
if (isPasswordCorrect(input)) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected");
}
//Zero out the possible password, for security.
Arrays.fill(input, '0');
Passwordfld.selectAll();
/*else{
System.out.println("permition Rejected");
}*/
//else{}
/* if (Passwordfld = Password)= true) {
System.out.println("permition granted");}*/
}
}
}
);
Cancelbtn = new JButton();
getContentPane().add(Cancelbtn);
Cancelbtn.setText("Exit");
Cancelbtn.setBounds(198, 217, 61, 23);
Cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setDefaultCloseOperation(WindowConstants.setVisible(false);
//System.out.println("Cancelbtn.actionPerformed, event="+evt);
//TODO add your code for Cancelbtn.actionPerformed
}
});
Welco = new JLabel();
getContentPane().add(Welco);
Welco.setText("Welcome to Jstore please log in using your staff acount");
Welco.setBounds(51, 19, 291, 16);
JPasswordField Passwordfld = new JPasswordField();
//Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.out.println("Passwordfld.actionPerformed, event="+evt);
//TODO add your code for Passwordfld.actionPerformed
}
});
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
//static class AL implements ActionListener{
//JPasswordField input = new JPasswordField();
/* char [] passy = input.getPassword();
String p = new String (passy);{
if (p.equals (Password)){
JOptionPane.showMessageDialog(null, "Correct"); }
else
{ JOptionPane.showMessageDialog(null, "InCorrect");
}
*/
}
Alternatively you can use this....
package javaapplication7;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* #author akash
*/
public class detail extends javax.swing.JFrame implements ActionListener{
private final String username ="admin";
private final String password = "pass";
public detail() {
initComponents();
jButton1.addActionListener(this);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Username");
jLabel2.setText("Password");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Submit");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(detail.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 detail().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== jButton1)
{
if("admin".equals(jTextField1.getText()) && "pass".equals(jTextField2.getText()))
{
java.awt.EventQueue.invokeLater(() -> {
new LoggedIn().setVisible(true);
});
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use admin and pass");
}
}
}
}
The above one will be your first class and the next will be....
class LoggedIn extends javax.swing.JFrame {
/**
* Creates new form LoggedIn
*/
public LoggedIn() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Welcome 2 Store");
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(91, 91, 91)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(101, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(163, 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(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Hoping it helped....
Your password field is not inited, it's still null when you try to take char[] from it. You can try with:
final JPasswordField Passwordfld = new JPasswordField();
// Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println("Passwordfld.actionPerformed, event="+evt);
// TODO add your code for Passwordfld.actionPerformed
}
});
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String passText = new String(Passwordfld.getPassword());
if (Usernametxt.getText().equals("Admin")) {
String cmd = evt.getActionCommand();
if (OKbtn.getActionCommand().equals(cmd)) { // Process the password.
if (isPasswordCorrect(passText.toCharArray())) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected: " + passText);
}
// Zero out the possible password, for security.
Arrays.fill(passText.toCharArray(), '0');
Passwordfld.selectAll();
/*
* else{ System.out.println("permition Rejected"); }
*/
// else{}
/*
* if (Passwordfld = Password)= true) {
* System.out.println("permition granted");}
*/
}
}
}
});

Automatically traverse a dynamically created jPanels for component values

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

Passing a value from a JFrame to another JFrame

I have the code to do this, but I can't do it. I made something similar and worked without problem ( and asked here too) . Basically I am trying to pass the username that I enter into my textbox to a label from my otherJFrame ( I know it's not good practice to have 2 JFrames ).
The code where I try to parse my data is supposed to happen here :
if( rs.next() )
{
JOptionPane.showMessageDialog(null, "Successfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);
this.setVisible(false);
new FrmMain2(username).setVisible(true);
}
This is the whole code from the 1'st frame
/*
* 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 mysqltryouts;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* #author ExtremeSwat
*/
public class login_panel extends javax.swing.JFrame {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void readDataBase() throws Exception
{
String username = jTextField1.getText();
String password = jPasswordField1.getText();
// System.out.println(username);
// System.out.println(password);
// System.out.println("test");
//---------------------
// String databaseUsername = "";
// String databasePassword = "";
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/cards?"
+ "user=root&password=password");
//String sqlQuery = "select count(*) > 0 as match_found FROM username WHERE username = ? and password = MD5(?)";
String sqlQuery = "SELECT * FROM username WHERE username = ? and password = MD5(?)";
// String sqlQuery = "select count(*) > 0 as cnt FROM username WHERE username = ? and password = MD5(?)";
PreparedStatement pst = connect.prepareStatement( sqlQuery );
pst.setString( 1, username );
pst.setString( 2, password );
ResultSet rs = pst.executeQuery();
if( rs.next() )
{
JOptionPane.showMessageDialog(null, "Successfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);
//this.setVisible(false);
//new FrmMain().setVisible(true);
//this.setVisible(false);
//new FrmMain(username).setVisible(true);
this.setVisible(false);
new FrmMain2(username).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "Failed to log in", "Failure", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void close() {
close(resultSet);
close(statement);
close(connect);
}
private void close(AutoCloseable c) throws UnsupportedOperationException {
try {
if (c != null) {
c.close();
}
} catch (Exception e) {
// don't throw now as it might leave following closables in undefined state
}
}
/**
* Creates new form login_panel
*/
public login_panel() {
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() {
jTextField1 = new javax.swing.JTextField();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jPasswordField1ActionPerformed(evt);
}
});
jLabel1.setText("Username");
jLabel2.setText("Password");
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("eXIT");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Old English Text MT", 1, 36)); // NOI18N
jLabel3.setText("Login B0$$");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton2)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(53, 53, 53))))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addGap(4, 4, 4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addComponent(jButton2))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
// login_panel dao = new login_panel();
//
//
// dao.readDataBase();
this.readDataBase();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Exit? ", "Information",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Thanks for the stay","Confirm",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}else
{
JOptionPane.showMessageDialog(null, "Remaining...","Remaining....",JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* #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(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login_panel.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 login_panel().setVisible(true);
login_panel frame = new login_panel();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
The code from the second form is
package mysqltryouts;
import javax.swing.*;
import java.awt.*;
//am cancer
public class FrmMain2 {
private String userName;
public FrmMain2(String username) {
this.userName=username;
gui();
}
public void gui()
{
JFrame f = new JFrame("Ma JFrame");
JPanel p = new JPanel();
p.setBackground(Color.YELLOW);
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b1 = new JButton("Back");
JLabel l1 = new JLabel("Username");
l1.setText(userName);
p.add(b1);
p.add(l1);
f.add(p);
f.setVisible(true);
}
public static void main(String[] args)
{
//new FrmMain2(username);
}
}
So I want to transfer the username String to my label from MainFrame2. I had a similar problem that I posted it here ( and solved) but I can't do it.....
You state:
I know it's not good practice to have 2 JFrames
Then don't do this. The login "JFrame" should be a modal JDialog. Period. End of Story.
Why?
Then the main GUI can call the dialog knowing that code control will return right back to the spot where the dialog was made visible once the dialog is no longer visible. Then it will be trivial for the main GUI to query the state of your dialog's user provided data and move forward.
For example: https://stackoverflow.com/a/21462653/522444
Just bite the bullet and do it and you won't regret it.

Netbeans Java CRUD application with custom swing interface

i'm trying to build a java application with an embedded database. It will be very similiar to a CRUD application and i looked deeply in many tutorials provided for oracle and netbeans like this ones:
http://platform.netbeans.org/tutorials/nbm-crud.html
http://netbeans.org/kb/70/java/gui-db.html
However, this build automatically a default interface based on just crud actions and that's not what i want. I pretend to customize by myself all the interface and when need, access the derby embedded database to execute some operations.
In the mean time i just have two .java files. The JFrame one which contains the code generated by the elements added on the design menu:
package interface_aquitex;
import aquitex.Aquitex;
import javax.swing.JOptionPane;
public class design_aquitex extends javax.swing.JFrame {
/**
* Creates new form design_aquitex
*/
public design_aquitex() {
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() {
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jFrame1.setMinimumSize(new java.awt.Dimension(400, 400));
jLabel1.setText("Nome:");
jLabel2.setText("Idade:");
jTextField1.setName(""); // NOI18N
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jTextField1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
jTextField1PropertyChange(evt);
}
});
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextField1KeyPressed(evt);
}
});
jButton1.setText("Inserir");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Dados");
jButton2.setText("Listar");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jFrame1Layout.createSequentialGroup()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(37, 37, 37)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
.addComponent(jTextField2)))
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton1))
.addGap(94, 94, 94))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5)
.addComponent(jButton1)
.addGap(4, 4, 4)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(88, 88, 88)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addContainerGap(79, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setText("jMenuItem1");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
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>
public String getjTextField1(){
JOptionPane.showMessageDialog(null,jTextField1.getText());
return jTextField1.getText();
}
public int getjTextField2(){
int idade;
idade = Integer.parseInt(jTextField2.getText());
System.out.println(idade);
return idade;
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
jFrame1.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Aquitex a = new Aquitex();
a.saveRecord();
}
private void jTextField1PropertyChange(java.beans.PropertyChangeEvent evt) {
// TODO add your handling code here:
}
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
JOptionPane.showMessageDialog(null,jTextField1.getText());
}
/**
* #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(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(design_aquitex.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 design_aquitex().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JFrame jFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}
and the one with a class created by me:
package aquitex;
import interface_aquitex.design_aquitex;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Aquitex extends JFrame{
private static PreparedStatement stmtSaveNewRecord=null;
private static Connection dbConnection = null;
String tabelaExp =
"CREATE table APP.Alunos ("+
" ID INTEGER NOT NULL"+
" PRIMARY KEY GENERATED ALWAYS AS IDENTITY "+
" (START WITH 1, INCREMENT BY 1),"+
"FIRSTNAME VARCHAR(30),"+
"AGE INT )";
private void setDBSystemDir() {
// Decide on the db system directory: <userhome>/.aquitex/
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.aquitex";
// Set the db system directory.
System.setProperty("derby.system.home", systemDir);
}
private boolean createTables(Connection dbConnection) {
boolean bCreatedTables = false;
Statement statement = null;
try {
statement = dbConnection.createStatement();
statement.execute(tabelaExp);
bCreatedTables = true;
} catch (SQLException ex) {
ex.printStackTrace();
}
return bCreatedTables;
}
public int saveRecord() {
design_aquitex da = new design_aquitex();
try {
stmtSaveNewRecord = dbConnection.prepareStatement(
"INSERT INTO APP.Alunos " +
" (FIRSTNAME, AGE) " +
"VALUES (?, ?)",
Statement.RETURN_GENERATED_KEYS);
} catch (SQLException ex) {
Logger.getLogger(Aquitex.class.getName()).log(Level.SEVERE, null, ex);
}
int id = -1;
try {
stmtSaveNewRecord.clearParameters();
stmtSaveNewRecord.setString(1, da.getjTextField1());
stmtSaveNewRecord.setInt(2, da.getjTextField2());
int rowCount = stmtSaveNewRecord.executeUpdate();
ResultSet results = stmtSaveNewRecord.getGeneratedKeys();
if (results.next()) {
id = results.getInt(1);
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
return id;
}
public static void main(String[] args) {
// TODO code application logic here
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.aquitex";
// Set the db system directory.
System.setProperty("derby.system.home", systemDir);
String strUrl = "jdbc:derby:aquitex_db;create=true";
Properties props = new Properties();
props.put("user", "adm_aquitex");
props.put("password", "pass_aquitex");
try {
dbConnection = DriverManager.getConnection(strUrl, props);
} catch (SQLException ex) {
Logger.getLogger(Aquitex.class.getName()).log(Level.SEVERE, null, ex);
}
//Aquitex a = new Aquitex();
//a.createTables(dbConnection);
design_aquitex da = new design_aquitex();
da.setVisible(true);
}
}
For now, what i really need is some lights in how to separate the interface from the database i mean, use a "class" or something between them so that they don't "contact" each other.
And my other question is about the tables that i have on the database. Will they need a class.java file for each of them? And what about the Entity Manager Class presented in this tutorial:
http://platform.netbeans.org/tutorials/nbm-crud.html
Will i need to use it? I'm using derby database.
Sory for a so long questio, but i'm a bit lost at the moment in how to make the structure in what is supposed to be a java crud desktop application with a custom interface, and in how to make the layers ("swing","db" and the one that separates them") connect between each other.
1) your first file (what is it's name?) should have all the GUI stuff.
2) Your second file ("Aquitex.java"?) should not extend from JFrame, and should not necessarily have any GUI stuff.
3) Your main form will create an instance of "Aquitex".
4) UI event handlers in the first class will call public methods in the second.

How to wire one pane to another

How do I wire output to paneWithList?
PaneWithList has a listener on its JList so that the selected row is output to the console. How can I direct that output to the JTextPane on output?
Could PaneWithList fire an event which Main picks up? Would PropertyChangeSupport suffice?
Main.java:
package dur.bounceme.net;
import javax.swing.JTabbedPane;
public class Main {
private static JTabbedPane tabs;
private static PaneWithList paneWithList;
private static PaneWithTable paneWithTable;
private static Output output;
public static void main(String[] args) {
tabs = new javax.swing.JTabbedPane();
paneWithList = new PaneWithList();
paneWithTable = new PaneWithTable();
tabs.addTab("list", paneWithList);
tabs.addTab("table", paneWithTable);
tabs.addTab("output", output);
}
}
Here's an example using the observer pattern, also seen here, here and here. Note that it would also be possible to listen to the combo's model.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
/**
* #see http://en.wikipedia.org/wiki/Observer_pattern
* #see https://stackoverflow.com/a/10523401/230513
*/
public class PropertyChangeDemo {
public PropertyChangeDemo() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new ObserverPanel());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PropertyChangeDemo example = new PropertyChangeDemo();
}
});
}
}
class ObserverPanel extends JPanel {
private JLabel title = new JLabel("Value received: ");
private JLabel label = new JLabel("null", JLabel.CENTER);
public ObserverPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObserverPanel"));
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(title);
panel.add(label);
this.add(panel);
ObservedPanel observed = new ObservedPanel();
observed.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(ObservedPanel.PHYSICIST)) {
String value = e.getNewValue().toString();
label.setText(value);
}
}
});
this.add(observed);
}
}
class ObservedPanel extends JPanel {
public static final String PHYSICIST = "Physicist";
private static final String[] items = new String[]{
"Alpher", "Bethe", "Gamow", "Dirac", "Einstein"
};
private JComboBox combo = new JComboBox(items);
private String oldValue;
public ObservedPanel() {
this.setBorder(BorderFactory.createTitledBorder("ObservedPanel"));
combo.addActionListener(new ComboBoxListener());
this.add(combo);
}
private class ComboBoxListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
String newValue = (String) combo.getSelectedItem();
firePropertyChange(PHYSICIST, oldValue, newValue);
oldValue = newValue;
}
}
}
I'd be use JMenu with JMenuItems with contents layed by using CardLayout rather than very complicated JTabbedPane(s)
For my own reference, and for anyone using the Netbeans GUI builder, this works so far as it goes:
The PanelWithList class:
package dur.bounceme.net;
public class PanelWithList extends javax.swing.JPanel {
public PanelWithList() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jList1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jList1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2)
.addComponent(jScrollPane1))
.addContainerGap(166, Short.MAX_VALUE))
);
}// </editor-fold>
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
row();
}
private void jList1KeyReleased(java.awt.event.KeyEvent evt) {
row();
}
// Variables declaration - do not modify
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
private void row() {
Object o = jList1.getSelectedValue();
String s = (String)o;
jTextArea1.setText(s);
this.firePropertyChange("list", -1, 1);
}
}
and Frame.java as a driver:
package dur.bounceme.net;
public class Frame extends javax.swing.JFrame {
public Frame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
panelWithList1 = new dur.bounceme.net.PanelWithList();
panelWithTable1 = new dur.bounceme.net.PanelWithTable();
newJPanel1 = new dur.bounceme.net.PanelWithCombo();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panelWithList1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
panelWithList1PropertyChange(evt);
}
});
jTabbedPane1.addTab("tab1", panelWithList1);
jTabbedPane1.addTab("tab2", panelWithTable1);
jTabbedPane1.addTab("tab3", newJPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 937, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 555, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void panelWithList1PropertyChange(java.beans.PropertyChangeEvent evt) {
System.out.println("panelWithList1PropertyChange ");
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTabbedPane jTabbedPane1;
private dur.bounceme.net.PanelWithCombo newJPanel1;
private dur.bounceme.net.PanelWithList panelWithList1;
private dur.bounceme.net.PanelWithTable panelWithTable1;
// End of variables declaration
}
The key being that panelWithList1PropertyChange is the listener on 'panelWithList' itself.
Because PanelWithList.firePropertyChange("list", -1, 1); cannot send Object nor String that I see, I'm not exactly sure how to get the value selected all the way from the JList up to the JFrame.
Hmm, well the API says yes it can send Objects. Have to check that out.
I think it's necessary to get some info about the model which the JList is using up to the JFrame. However, doesn't that break MVC? Or maybe that's the wrong approach.

Categories