How do I access a string from a class - java

how would I access the entered value "Username" from another class? inside the package
I'm having trouble coding that. Should I declare some variable public?
I declared the Username public, but I get errors
this is my code:
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JOptionPane;
#SuppressWarnings("serial")
public class Login extends javax.swing.JFrame {
public Login() {
initComponents0();
}
#SuppressWarnings("unchecked")
private void initComponents0() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
uname = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
login = new javax.swing.JButton();
reset = new javax.swing.JButton();
pwd = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Login Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
login.setText("Login");
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String un = uname.getText();
#SuppressWarnings("deprecation")
String pw = pwd.getText();
try{
FileInputStream fstream = new FileInputStream("data.dat");
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
boolean registered = false;
boolean registered0 = false;
while ((strLine = br.readLine()) != null) {
String values[] = strLine.split("\\|");
if ((strLine.startsWith(un))&&(pw.equals(values[1]))){
registered = true;
break;
}
if ((strLine.startsWith(un))&&(!pw.equals(values[1]))){
registered0 = true;
break;
}
}
if(registered){
JOptionPane.showMessageDialog(null,"Hello: "+un ,"Registration",JOptionPane.INFORMATION_MESSAGE);
File file = new File("temp.dat");
try {
try (FileWriter writer = new FileWriter(file, false)) {
String data0 = un;
writer.write(data0);
}}
catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
else if(registered0){JOptionPane.showMessageDialog(null,"It seems you entered a wrong password! \n Please try again " ,"Admin",JOptionPane.INFORMATION_MESSAGE);}
else
{
int sel = JOptionPane.showConfirmDialog(null,"It seems that you haven't registered yet? \n Launch Registration Pane?","Admin",JOptionPane.INFORMATION_MESSAGE);
if (sel == JOptionPane.YES_OPTION){
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Register().setVisible(true);
}});}
}}}
catch ( IOException | HeadlessException ez){
JOptionPane.showMessageDialog(null,"A null file was created in order to \n avoid File Catch errors","Admin",JOptionPane.INFORMATION_MESSAGE);
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = "null";
String data1 = "null";
writer.write(data0+" | "+data1+"\n");
}}
catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
}});
reset.setText("Reset Field");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
uname.setText("");
pwd.setText("");
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(pwd))))
.addContainerGap(30, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(login)
.addComponent(reset))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton login;
private javax.swing.JPasswordField pwd;
private javax.swing.JButton reset;
private javax.swing.JTextField uname;
// End of variables declaration
}
edited
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JOptionPane;
#SuppressWarnings("serial")
public class Login extends javax.swing.JFrame {
private String username,password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public Login() {
initComponents0();
}
#SuppressWarnings("unchecked")
private void initComponents0() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
uname = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
login = new javax.swing.JButton();
reset = new javax.swing.JButton();
pwd = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Login Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
login.setText("Login");
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String un = uname.getText();
#SuppressWarnings("deprecation")
String pw = pwd.getText();
username = un;
password = pw;
try{
FileInputStream fstream = new FileInputStream("data.dat");
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
boolean registered = false;
boolean registered0 = false;
while ((strLine = br.readLine()) != null) {
String values[] = strLine.split("\\|");
if ((strLine.startsWith(un))&&(pw.equals(values[1]))){
registered = true;
break;
}
if ((strLine.startsWith(un))&&(!pw.equals(values[1]))){
registered0 = true;
break;
}
}
if(registered){
username = un;
password = pw;
JOptionPane.showMessageDialog(null,"Hello: "+un ,"Registration",JOptionPane.INFORMATION_MESSAGE);
File file = new File("temp.dat");
try {
try (FileWriter writer = new FileWriter(file, false)) {
String data0 = un;
writer.write(data0);
}}
catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
else if(registered0){JOptionPane.showMessageDialog(null,"It seems you entered a wrong password! \n Please try again " ,"Admin",JOptionPane.INFORMATION_MESSAGE);}
else
{
int sel = JOptionPane.showConfirmDialog(null,"It seems that you haven't registered yet? \n Launch Registration Pane?","Admin",JOptionPane.INFORMATION_MESSAGE);
if (sel == JOptionPane.YES_OPTION){
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Register().setVisible(true);
}});}
}}}
catch ( IOException | HeadlessException ez){
JOptionPane.showMessageDialog(null,"A null file was created in order to \n avoid File Catch errors","Admin",JOptionPane.INFORMATION_MESSAGE);
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = "null";
String data1 = "null";
writer.write(data0+" | "+data1+"\n");
}}
catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
}});
reset.setText("Reset Field");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
uname.setText("");
pwd.setText("");
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(pwd))))
.addContainerGap(30, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(login)
.addComponent(reset))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
/*
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton login;
private javax.swing.JPasswordField pwd;
private javax.swing.JButton reset;
private javax.swing.JTextField uname;
// End of variables declaration
}

Make private global non-static fields to hold the username and password fields, when you accept the input assign the values to your global username and password variables. Then have getter method(s) which are public and return the username and password for that instance.
something like:
public class Login extends javax.swing.JFrame {
private String username,password;//assign private global fields for the instance
//the variables are assigned when you accept user input
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
you'd then do something like:
Login lg=new Login();//create new instance to gain access to getter methods
//wait for it to return or until user has enetered the credentials
System.out.println(lg.getUsername());
System.out.println(lg.getPassword());

You need to have public setters and getters for you private variables in order to call or edit your private variables from out side of your class. This is called as encapsulation one of the important concept of OOP. You may want to google for it know more.

Declare the variable in global scope and also declare those variables with Public access specifier. Or
use getter method for Private declared variables .And make those getter method Public.

Related

problems when receiving data from jframe

I've been trying to add values to a list inside a class from a separated jFrame. I tested and know that the information is sending correctly and the function to receive this information is also receiving it correctly. The problem is that Im not sure if the information is being added into the list, because when i try to print it, nothing happens.
import java.util.ArrayList;
public class Conta {
private int NumConta;
private String Nome;
private String RG;
private String CPF;
private double Saldo;
private String Password;
ArrayList<Conta> ListaUser;
public Conta(){
ListaUser = new ArrayList();
}
public Conta(int NumConta, String Nome, String RG, String CPF, double Saldo, String Password) {
this.NumConta = NumConta;
this.Nome = Nome;
this.RG = RG;
this.CPF = CPF;
this.Saldo = Saldo;
this.Password = Password;
ListaUser = new ArrayList();
}
public int getNumConta() {
return NumConta;
}
public void setNumConta(int NumConta) {
this.NumConta = NumConta;
}
public String getNome() {
return Nome;
}
public void setNome(String Nome) {
this.Nome = Nome;
}
public String getRG() {
return RG;
}
public void setRG(String RG) {
this.RG = RG;
}
public String getCPF() {
return CPF;
}
public void setCPF(String CPF) {
this.CPF = CPF;
}
public double getSaldo() {
return Saldo;
}
public void setSaldo(double Saldo) {
this.Saldo = Saldo;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public ArrayList<Conta> getListaUser() {
return ListaUser;
}
public void setListaUser(ArrayList<Conta> ListaUser) {
this.ListaUser = ListaUser;
}
public void AddFunc(Conta C){
ListaUser.add(C);
}
}
This is the class which receives information
import java.util.Random;
import javax.swing.JOptionPane;
public class Cadastrar extends javax.swing.JFrame {
public Cadastrar() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanelinicio = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextFieldnomecadastro = new javax.swing.JTextField();
jTextFieldRG = new javax.swing.JTextField();
jTextFieldCPF = new javax.swing.JTextField();
jTextFieldpasswordcadastro = new javax.swing.JTextField();
jButtonconfirmarcadastro = new javax.swing.JButton();
jButtonvoltarCadastrar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanelinicio.setBackground(new java.awt.Color(102, 153, 255));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setText("RG:");
jLabel2.setText("CPF:");
jLabel3.setText("Nome:");
jLabel4.setText("Password:");
jButtonconfirmarcadastro.setText("Confirmar");
jButtonconfirmarcadastro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonconfirmarcadastroActionPerformed(evt);
}
});
jButtonvoltarCadastrar.setText("Voltar");
jButtonvoltarCadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonvoltarCadastrarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel4))
.addGap(58, 58, 58)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldpasswordcadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldRG, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldnomecadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(77, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonconfirmarcadastro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonvoltarCadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(173, 173, 173))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(56, 56, 56)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldnomecadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextFieldRG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(43, 43, 43)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextFieldCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(jTextFieldpasswordcadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(68, 68, 68)
.addComponent(jButtonconfirmarcadastro)
.addGap(18, 18, 18)
.addComponent(jButtonvoltarCadastrar)
.addContainerGap(28, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelinicioLayout = new javax.swing.GroupLayout(jPanelinicio);
jPanelinicio.setLayout(jPanelinicioLayout);
jPanelinicioLayout.setHorizontalGroup(
jPanelinicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanelinicioLayout.setVerticalGroup(
jPanelinicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelinicioLayout.createSequentialGroup()
.addGap(0, 117, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelinicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelinicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jButtonvoltarCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
Principal principal = new Principal();
principal.setVisible(true);
dispose();
}
private void jButtonconfirmarcadastroActionPerformed(java.awt.event.ActionEvent evt) {
Random random = new Random();
int numero = random.nextInt(9999999);
Conta C = new Conta(numero,jTextFieldnomecadastro.getText(),jTextFieldRG.getText(),jTextFieldCPF.getText(),0,jTextFieldpasswordcadastro.getText());
C.AddFunc(C);
JOptionPane.showMessageDialog(this, "Conta criada com sucesso!\n"+"Numero da conta: "+numero);
Principal p = new Principal();
p.setVisible(true);
dispose();
}
/**
* #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(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Cadastrar.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 Cadastrar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonconfirmarcadastro;
private javax.swing.JButton jButtonvoltarCadastrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelinicio;
private javax.swing.JTextField jTextFieldCPF;
private javax.swing.JTextField jTextFieldRG;
private javax.swing.JTextField jTextFieldnomecadastro;
private javax.swing.JTextField jTextFieldpasswordcadastro;
// End of variables declaration
}
This jFrame sends the information.
How can I make the list receive information and how can I see all the information added?
Thanks in advance
Each Conta has it's own copy of ListaUser so when you do
Conta C = new Conta(...);
C.AddFunc(C);
You are adding C to C's own copy of ListaUser, and each Conta C will contain a List ListaUser that has only one element in the list; the C itself. Stated another way, each Conta will have a list with only itself as the list contents; there is no list that contains all of the Conta's that you have created.
An Account (Conta) should not be the place that maintains the list of accounts your program is keeping. It is the program itself that is concerned with the accounts, so the program has-a list of accounts.
public class Cadastrar extends javax.swing.JFrame {
private List<Conta> listaUser = new ArrayList<>();
private Cadastrar program;
public Cadastrar() {
initComponents();
program = this;
}
// etc.
Later in the program in jButtonconfirmarcadastroActionPerformed when you create a Conta you would add it to the program's list
Conta c = new Conta(...);
program.listaUser.add(c);
// or possibly: program.storeConta(c);
At some point in your program you might want to show the list, maybe in response to another button-press, which might look something like this, if you were just printing to the console (I'm not going to write code here to display it in a JPanel or anything)
// other methods that are in class Cadastrar
List<Conta> getContaList()
{
return program.listaUser;
}
void listContas()
{
for (Conta c : program.getContaList()) {
System.out.println(c);
}
}
Often you might use this instead of keeping a separate variable program
Notice also that I changed the case of variable names… it is not a hard rule, but is a convention in Java that class names should start with uppercase, like Conta but variable names start with lowercase, like listaUser instead of ListaUser.
I haven't done Swing programming in a long time, but it is (or was?) also common practice to have an Application object that is separate from your main JFrame, so you might have this sort of arrangement...
public class MyApplication
{
// the Program owns the list, which the JFrame will use
private static final List<Conta> listaUser = new ArrayList<>();
// because we pass the list to the application window in `main`
Cadastrar appWindow;
public static void main(String... args)
{
// here is where you would do your LookAndFeel initialization,
// and create an instance of your application's main window
appWindow = new Cadastrar(listaUser);
// obviously this sample code is incomplete, just to demonstrate
// that your Program sets up the environment and creates the
// main window which the User will interact with.
}
}

Having Trouble Serializing Data

I Am having trouble saving the state of a Form application and loading its state. I created a simple Swing Application in Java using netbeans. The purpose of the program is a spit out a unique 4 digit number and had a note if necessary. The trouble came up with I tried to serialize the data so that when the application was opened again I would be able to load the data from where I left off.
Here is the code for the Swing Portion:
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* 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 marcsantiago
*/
public class MainForm extends javax.swing.JFrame {
/**
* Creates new form MainForm
*/
public MainForm() {
//jTextField2.setVisible(false);
this.rndn = new RandomNumber();
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jCheckBox1 = new javax.swing.JCheckBox();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField3 = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Generate Number");
jButton1.setToolTipText("");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setToolTipText("");
jCheckBox1.setText("Add Notes");
jButton2.setText("Save Note and Number");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("View Notes");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton4.setText("Save All Data");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Load Data");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jCheckBox1)))
.addGap(0, 82, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(111, 111, 111))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public RandomNumber rndn;
//View Randomly Generated Number buttom
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(rndn.getNumber());
}
//save number button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jCheckBox1.isSelected()){
String text = jTextField3.getText();
rndn.removeNumber(text);
}else{
rndn.removeNumber("");
}
}
//view notes
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,String> entry : rndn.getSaveState().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append("ID: ").append(key).append("\t");
sb.append("Note: ").append(value).append("\n");
}
jTextArea1.setText(sb.toString());
}
//save data
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader txtReader = rndn.getTxtReader();
ArrayList<String> numbers = rndn.getNumbers();
ArrayList<String> usedNumbers = rndn.getUsedNumbers();
String currentNumber = rndn.getCurrentNumber();
Map<String, String> saveState = rndn.getSaveState();
try
{
FileOutputStream fileOut = new FileOutputStream("/tmp/data.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(rndn);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
//load data
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// try
// {
// FileInputStream fileIn = new FileInputStream("/tmp/data.ser");
// ObjectInputStream in = new ObjectInputStream(fileIn);
// rndn = (RandomNumber) in.readObject();
// in.close();
// fileIn.close();
// }catch(IOException i)
// {
// i.printStackTrace();
// return;
// }catch(ClassNotFoundException c)
// {
// System.out.println("Employee class not found");
// c.printStackTrace();
// return;
// }
// System.out.println(rndn.getSaveState());
}
/**
* #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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}
near the end I've comment the two methods as //save and //load
That those methods I can't figure out. When I try and serialize the rndn object I get this error: java.io.NotSerializableException: java.io.BufferedReader
The class that contains the data is serrate from the Form Class:
Here is the RandomNumber class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/*
* 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 marcsantiago
*/
public class RandomNumber implements java.io.Serializable{
private BufferedReader txtReader;
private ArrayList<String> numbers;
private ArrayList<String> usedNumbers = new ArrayList<>();
private Random rnd = new Random();
private String currentNumber;
private Map<String, String> saveState = new HashMap<>();
RandomNumber(){
this.txtReader = new BufferedReader(new InputStreamReader(RandomNumber.class.getResourceAsStream("/resources/unique_nums")));
try{
numbers = new ArrayList(Arrays.asList(txtReader.readLine().split(",")));
}catch(IOException e){
}
}
public String getNumber(){
int item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
while(usedNumbers.contains(currentNumber)){
item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
}
return currentNumber;
}
public void removeNumber(String note){
usedNumbers.add(currentNumber);
saveState.put(currentNumber, note);
numbers.remove(currentNumber);
}
public ArrayList<String> getUsedNumbers() {
return usedNumbers;
}
public String getCurrentNumber() {
return currentNumber;
}
public Map<String, String> getSaveState() {
return saveState;
}
public void setTxtReader(BufferedReader txtReader) {
this.txtReader = txtReader;
}
public BufferedReader getTxtReader() {
return txtReader;
}
public ArrayList<String> getNumbers() {
return numbers;
}
public Random getRnd() {
return rnd;
}
public void setNumbers(ArrayList<String> numbers) {
this.numbers = numbers;
}
public void setUsedNumbers(ArrayList<String> usedNumbers) {
this.usedNumbers = usedNumbers;
}
public void setRnd(Random rnd) {
this.rnd = rnd;
}
public void setCurrentNumber(String currentNumber) {
this.currentNumber = currentNumber;
}
public void setSaveState(Map<String, String> saveState) {
this.saveState = saveState;
}
}
Sorry if it's a bit messy, I haven't cleaned up the code yet because I haven't gotten it to work the way I want to to. Any help in completing this application is much appreciated.
The BufferedReader in your class is not seriablizeable and that should be causing the issue. Make it transient and it should work.

JComboBox dynamically updating values

I am trying to update the items of the combo box with the xml nodes, I get the nodes when I run the loop, however somehow I am not able to add them as the items of ComboBox
public class XMLtoExcelGUI extends javax.swing.JFrame {
public java.io.File file;
public XMLtoExcelGUI() {
initComponents();
}
public void setProgressBarValue(String s){
jProgressBar1.setString(s);
}
#SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("XMLToExcel");
jButton1.setText("Choose File");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Select Measures");
jProgressBar1.setStringPainted(true);
jButton3.setText("Get Measure Data");
jScrollPane1.setViewportView(jTextPane1);
jComboBox1.setMaximumRowCount(30);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
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(137, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(127, 127, 127))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(117, 117, 117))))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(63, 63, 63)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
TestVDT call = new TestVDT(file);
jTextPane1.setText(file.toString());
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(XMLtoExcelGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new XMLtoExcelGUI().setVisible(true);
}
});
}
public javax.swing.JButton jButton1;
public javax.swing.JButton jButton3;
public javax.swing.JComboBox jComboBox1;
public javax.swing.JLabel jLabel1;
public javax.swing.JLabel jLabel2;
public javax.swing.JProgressBar jProgressBar1;
public javax.swing.JScrollPane jScrollPane1;
public javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
public class TestVDT {
public int setNumberOfMeasures = 0;
public String[] Measures = new String[30];
public void setMeasureValues(String S[], int length) {
Vector comboBoxItems = new Vector();
for (int i = 1; i < length; i++) {
comboBoxItems.add(S[i]);
// System.out.println(S[i]);
}
XMLtoExcelGUI call = new XMLtoExcelGUI();
DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(comboBoxItems);
call.jComboBox1.setModel(defaultComboBoxModel);
}
public TestVDT(java.io.File FName) {
try {
File f = new File(FName.toString());
FileInputStream fis = new FileInputStream(f);
byte[] ba = new byte[(int) f.length()];
fis.read(ba);
VTDGen vg = new VTDGen();
vg.setDoc(ba);
vg.parse(false);
VTDNav vn = vg.getNav();
FileOutputStream fout = new FileOutputStream("E:\\Data.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Data");
Row row1 = worksheet.createRow(0);
row1.createCell(0).setCellValue("Measure_id");
row1.createCell(1).setCellValue("Denominator");
row1.createCell(2).setCellValue("Numerator");
row1.createCell(3).setCellValue("exclusion");
row1.createCell(4).setCellValue("performance criteria");
//for(int i=0;i<3;i++)
int rowIndex = 1;
int j = 1;
vn.toElement(VTDNav.FIRST_CHILD);
do {
if (vn.matchElement("practice_data")) {
vn.toElement(VTDNav.FIRST_CHILD);
}
if (vn.matchElement("provider_data")) {
vn.toElement(VTDNav.FIRST_CHILD);
}
if (vn.matchElement("provider_identification")) {
vn.toElement(VTDNav.FIRST_CHILD);
}
if (vn.matchElement("measure")) {
vn.toElement(VTDNav.FIRST_CHILD);
do {
Row row = worksheet.createRow(rowIndex++);
int cellIndex = 0;
String temp = vn.toString(vn.getAttrVal("measure_id"));
System.out.println(temp);
Measures[j] = temp;
row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("measure_id")));
System.out.print(" -- ");
System.out.print(vn.toString(vn.getAttrVal("denominator")));
row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("denominator")));
System.out.print(" -- ");
System.out.print(vn.toString(vn.getAttrVal("numerator")));
row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("numerator")));
System.out.print(" -- ");
System.out.print(vn.toString(vn.getAttrVal("exclusion")));
row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("exclusion")));
System.out.print(" -- ");
System.out.println(vn.toString(vn.getAttrVal("performance_rate")));
row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("performance_rate")));
setNumberOfMeasures++;
j++;
} while (vn.toElement(VTDNav.NEXT_SIBLING));
}
} while (vn.toElement(VTDNav.NEXT_SIBLING));
System.out.println(setNumberOfMeasures);
workbook.write(fout);
fout.flush();
setMeasureValues(Measures, setNumberOfMeasures);
} catch (Exception e) {
System.out.println("exception occurred ==>" + e);
}
}
#SuppressWarnings("empty-statement")
public static void main(String[] args) {
}
}
By default the values of Jcombo box is blank and when the function setMeasureValues() is called it should update the items of the combo box but is not
Your XMLtoExcelGUI variable, call, is local to the setMeasureValues(...) method. Any changes made to the object that it refers to will only be reflected in this local object and not on any other object of similar type. A guess, but perhaps you want to pass into the method a valid reference to the displayed XMLtoExcelGUI object. Otherwise if this doesn't help, you're going to likely have to improve your question by telling and showing more.
Yes, I was right -- you're setting the model of a combo box in a completely different non-displayed XMLtoExcelGUI instance. Changing the state of one instance will not and should not have an effect on another. The solution is to change the state of the correct displayed instance.
Change this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
TestVDT call = new TestVDT(file);
jTextPane1.setText(file.toString());
}
}
to something like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
TestVDT call = new TestVDT(this, file); // ****** changed
jTextPane1.setText(file.toString());
}
And then this
public class TestVDT {
public int setNumberOfMeasures = 0;
public String[] Measures = new String[30];
public TestVDT(java.io.File FName) {
to something like:
public class TestVDT {
public int setNumberOfMeasures = 0;
public String[] Measures = new String[30];
private XMLtoExcelGUI gui;
public TestVDT(XMLtoExcelGUI gui, java.io.File FName) {
this.gui = gui;
This way your method can use a reference to the actual displayed GUI:
public void setMeasureValues(String S[], int length) {
Vector comboBoxItems = new Vector();
for (int i = 1; i < length; i++) {
comboBoxItems.add(S[i]);
}
// XMLtoExcelGUI call = new XMLtoExcelGUI(); // **** no!
DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(comboBoxItems);
// give XMLtoExcelGUI a public method that sets
// its own combo box's model
gui.setComboModel(defaultComboBoxModel);
}

Java multithreading in JFrame

I want this code work with update JProgressBar and JTextArea while scanner is working, but I don't know how implement Threading. Is it possible?
This is my code:
UPDATED: It's a working version now, with "Stop" function. I added a "breakPoint" variable to break out from the for loop.
package main;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class PortScanner extends javax.swing.JFrame {
private doSomeStuff taskPortScanner;
private boolean breakPoint;
public PortScanner() {
initComponents();
}
private void portScan() {
int currentPort = 1;
try {
String hostname = hostNameTextField.getText();
int timeOut = (Integer) timeOutSpinner.getValue();
int minPort = Integer.parseInt(portMinTextField.getText());
int maxPort = Integer.parseInt(portMaxTextField.getText());
//set min and max value of progress bar
jProgressBar1.setMinimum(minPort);
jProgressBar1.setMaximum(maxPort);
//print out the address
InetAddress theAddress = InetAddress.getByName(hostname);
resultTextArea.append("IP adress: " + theAddress + "\n\n");
//check if port is open
for (currentPort = minPort; currentPort <= maxPort; currentPort++) {
//stop for loop
if (breakPoint == true) {
System.out.println("Portscanning stopped.");
break;
}
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, currentPort), timeOut);
//update textarea
resultTextArea.append("Service running on port " + currentPort + "\n");
socket.close();
} catch (Exception ex) {
System.out.println(currentPort);
}
//update progressbar
jProgressBar1.setValue(currentPort);
jProgressBar1.repaint();
}
} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Unknown hostname: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Invalid format. " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
private class doSomeStuff extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() throws Exception {
portScan();
return null;
}
#Override
public void done() {
//if thread is done enable start and clear buttons
clearButton.setEnabled(true);
startButton.setEnabled(true);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
hostNameTextField = new javax.swing.JTextField();
portMinTextField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
resultTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
portMaxTextField = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
timeOutSpinner = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
stopButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simple port scanner");
setResizable(false);
jLabel1.setText("Hostname");
jLabel2.setText("Timeout");
jLabel3.setText("Port range");
hostNameTextField.setToolTipText("Type a hostname like www.google.com");
portMinTextField.setText("1");
resultTextArea.setColumns(20);
resultTextArea.setRows(5);
jScrollPane1.setViewportView(resultTextArea);
startButton.setText("Scan");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
clearButton.setText("Clear");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
portMaxTextField.setText("1000");
jProgressBar1.setStringPainted(true);
timeOutSpinner.setModel(new javax.swing.SpinnerNumberModel(15, 0, 999999, 1));
jLabel4.setText("-");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(timeOutSpinner)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(12, 12, 12)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(startButton)
.addGap(18, 18, 18)
.addComponent(stopButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(clearButton)
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(timeOutSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(clearButton)
.addComponent(stopButton))
.addContainerGap())
);
pack();
}// </editor-fold>
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = false;
taskPortScanner = new doSomeStuff();
taskPortScanner.execute();
startButton.setEnabled(false);
clearButton.setEnabled(false);
System.out.println("Starting portscanner...");
}
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
resultTextArea.setText(null);
jProgressBar1.setValue(0);
System.out.println("Clearing results...");
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = true;
startButton.setEnabled(true);
clearButton.setEnabled(true);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortScanner.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 PortScanner().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton clearButton;
private javax.swing.JTextField hostNameTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField portMaxTextField;
private javax.swing.JTextField portMinTextField;
private javax.swing.JTextArea resultTextArea;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
private javax.swing.JSpinner timeOutSpinner;
// End of variables declaration
}
You need to look at moving the long running scan task out of the Event dispatching thread to keep the UI responsive. Look at using a Swing Worker to achieve this.
http://en.wikipedia.org/wiki/SwingWorker#The_event_dispatching_thread_problem
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

give data from jtextfield and store them into file

I am going to write a library aplication program.
I work with netbeans.
i have an interface like this:
package Library;
public interface UserInformation {
public void setFName(String fn);
public String getFName();
public void setLName(String ln);
public String getLName();
public void setRegNum(int reg_num);
public int getRegNum();
public void setDate(int reg_date);
public int getDate();
}
and my NewUserDialog implements this interface:
private String FirstName="";
private String LastName="";
private int Registration_Number=0;
private int Date=0;
private String fileadress="AllUserRecords.txt";
public NewUserDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
// // <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tunga", 1, 14)); // NOI18N
jLabel1.setText("Add New User (Registration)");
jLabel2.setText("First Name:");
jLabel3.setText("Last Name:");
jLabel4.setText("Date:");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jButton1.setText("Create");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Back");
jLabel5.setText("Registration Number is:");
jLabel6.setText(" ");
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(54, 54, 54)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel5))
.addGap(98, 98, 98)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField3)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField2))
.addComponent(jLabel1)))
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jButton1)))
.addContainerGap(141, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(116, 116, 116))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
setFName(jTextField1.getText());
if(havedigit(FirstName)==true) throw new Exception();
WriteToFile(getFName());
setLName(jTextField2.getText());
if(havedigit(LastName)==true) throw new Exception();
WriteToFile(getLName());
setDate(Integer.parseInt(jTextField3.getText()));
WriteToFile(String.valueOf(getDate()));
Random rnd1=new Random();
Registration_Number=rnd1.nextInt(100);
setRegNum(Registration_Number);
WriteToFile(String.valueOf(getRegNum()));
jLabel6.setText(String.valueOf(getRegNum()));
}
catch(Exception e){
jLabel6.setText("Error!");
}
}
public boolean havedigit(String in){
for(int i=0;i<in.length();i++){
if(Character.isDigit(in.charAt(i))) return true;
}
return false;
}
public void WriteToFile(String content){
try{
File f=new File("C:\\userrecords.txt");
if(!f.exists()){
f.createNewFile();
}
else{
FileWriter fw=new FileWriter(f.getAbsoluteFile(), true);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(content);
bw.newLine();
bw.close();
System.out.println("Done");
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NewUserDialog dialog = new NewUserDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.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.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
public void setFName(String fn) {
FirstName.equals(fn);
}
public String getFName() {
return FirstName;
}
public void setLName(String ln) {
LastName.equals(ln);
}
public String getLName() {
return FirstName;
}
public void setRegNum(int reg_num) {
Registration_Number=reg_num;
}
public int getRegNum() {
return Registration_Number;
}
public void setDate(int reg_date) {
Date=reg_date;
}
public int getDate() {
return Date;
}
}
my purpose is that when we file the jtextfile fields and clicked the button, this data should save into a .txt file .
but both Fname and Lname did not save to file, just the "Date" file save to file.
and i want that Fname and Lname and Data must store regular in text file.
thanks!
Your setter methods, setFName(...) and setLName(...) don't do any setting at all. Instead all they do is perform an unnecessary and inexplicable test of equality and then discard the result:
public void setLName(String ln) {
LastName.equals(ln); // ???????
}
How about instead creating true setter methods that set the object held by a reference variable:
public void setLName(String ln) {
lastName = ln; // note variable names should begin w/ a lowercase letter
}
If you don't set these fields, then you can't expect the information from the getter methods to be useful when writing to file.
Also you have a weak catch block that does not inform you of the contents of the stack trace, information that may help you figure out what is wrong.
Also, what purpose is there for your GUI to implement a non-GUI interface that seems better suited for a model class, not a view (GUI) class? I would favor composition here instead of inheritance.

Categories