give data from jtextfield and store them into file - java

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.

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.
}
}

Java MVC - Multiple Views - Single Controller

I'm struggling here... I'm building a small calorie calculator application with Java swing using an MVC design pattern.
For some reason, the actionPerformed methods for my secondary view(SettingsView.java) don't do anything, yet for my main view(UserDetailsView.java) they work fine.
Here's my Controller class. (Simplified the code in the methods)
import com.willemdebruyn.macronutrientcalculator.model.Model;
import com.willemdebruyn.macronutrientcalculator.view.SettingsView;
import com.willemdebruyn.macronutrientcalculator.view.UserDetailsView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller
{
private UserDetailsView userDetailsView;
private SettingsView settingsView;
private Model model;
private double requiredCalories;
public Controller(UserDetailsView userDetailsView, SettingsView settingsView, Model model)
{
this.userDetailsView = userDetailsView;
this.settingsView = settingsView;
this.model = model;
this.userDetailsView.addCalorieCalculationListener(new CalorieCalculationListener()); // Here I add the listeners for my main view, they work just fine
this.userDetailsView.addMacroCalculationListener(new MacroCalculationListener());
this.settingsView.addApplySettingsListener(new ApplySettingsListener()); // This is the one that doesn't work
}
class CalorieCalculationListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This prints...");
}
}
class MacroCalculationListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This prints as well...");
}
}
class ApplySettingsListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("This never prints...");
}
}
}
Here's the methods that add the ActionListener in my UserDetailsView, which work as expected
public void addCalorieCalculationListener(ActionListener listenForCalorieButton)
{
caloriesButton.addActionListener(listenForCalorieButton);
}
public void addMacroCalculationListener(ActionListener listenForMacroButton)
{
macrosButton.addActionListener(listenForMacroButton);
}
Here is the code from my SettingsView to add the ActionListener (The one that doesn't work)
public void addApplySettingsListener(ActionListener listenForApplyButton)
{
applyButton.addActionListener(listenForApplyButton);
}
Am I missing something?
Edit:
As requested the SettingsView code
import java.awt.event.ActionListener;
public class SettingsView extends javax.swing.JFrame
{
/**
* Creates new form SettingsView
*/
public SettingsView()
{
initComponents();
myInit();
}
/**
* 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()
{
jLabel3 = new javax.swing.JLabel();
jInternalFrame1 = new javax.swing.JInternalFrame();
jInternalFrame2 = new javax.swing.JInternalFrame();
jLabel2 = new javax.swing.JLabel();
metricRadioButton = new javax.swing.JRadioButton();
imperialRadioButton = new javax.swing.JRadioButton();
jInternalFrame3 = new javax.swing.JInternalFrame();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox<>();
carbsTextField = new javax.swing.JTextField();
proteinsTextField = new javax.swing.JTextField();
fatsTextField = new javax.swing.JTextField();
applyButton = new javax.swing.JButton();
jLabel3.setText("jLabel3");
jInternalFrame1.setVisible(true);
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame2.setVisible(true);
jLabel2.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel2.setText("Measuring System:");
metricRadioButton.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
metricRadioButton.setText("Metric (cm/kg)");
metricRadioButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
metricRadioButtonActionPerformed(evt);
}
});
imperialRadioButton.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
imperialRadioButton.setText("Imperial (in/lbs)");
imperialRadioButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
imperialRadioButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame2Layout = new javax.swing.GroupLayout(jInternalFrame2.getContentPane());
jInternalFrame2.getContentPane().setLayout(jInternalFrame2Layout);
jInternalFrame2Layout.setHorizontalGroup(
jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame2Layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imperialRadioButton)
.addComponent(metricRadioButton)
.addComponent(jLabel2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jInternalFrame2Layout.setVerticalGroup(
jInternalFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(metricRadioButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imperialRadioButton)
.addGap(0, 16, Short.MAX_VALUE))
);
jInternalFrame3.setVisible(true);
jLabel4.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel4.setText("Carbs:");
jLabel5.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel5.setText("Proteins:");
jLabel6.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
jLabel6.setText("Fats:");
jLabel7.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel7.setText("Custom Macros:");
jLabel1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel1.setText("Macro Nutrients Split:");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "<Carbs/Proteins/Fats>", "50/30/20", "80/10/10", "Custom" }));
javax.swing.GroupLayout jInternalFrame3Layout = new javax.swing.GroupLayout(jInternalFrame3.getContentPane());
jInternalFrame3.getContentPane().setLayout(jInternalFrame3Layout);
jInternalFrame3Layout.setHorizontalGroup(
jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame3Layout.createSequentialGroup()
.addGap(110, 110, 110)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame3Layout.createSequentialGroup()
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fatsTextField)
.addComponent(proteinsTextField)
.addComponent(carbsTextField))))
.addComponent(jLabel1)))
.addContainerGap(111, Short.MAX_VALUE))
);
jInternalFrame3Layout.setVerticalGroup(
jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame3Layout.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(18, 18, 18)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(carbsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(proteinsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(fatsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 38, Short.MAX_VALUE))
);
applyButton.setText("Apply");
applyButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
applyButtonActionPerformed(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(jInternalFrame2)
.addComponent(jInternalFrame3)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(applyButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jInternalFrame2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jInternalFrame3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(applyButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void myInit()
{
// Metric radio button should be selected on default
metricRadioButton.setSelected(true);
// Disable textFields on startup
carbsTextField.setEditable(false);
proteinsTextField.setEditable(false);
fatsTextField.setEditable(false);
}
private void metricRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When metric radio button is selected, deselect the imperial radio button
imperialRadioButton.setSelected(false);
}
private void imperialRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When imperial radio button is selected, deselect the metric radio button
metricRadioButton.setSelected(false);
}
private void applyButtonActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("Apply button clicked");
}
public void addApplySettingsListener(ActionListener listenForApplyButton)
{
applyButton.addActionListener(listenForApplyButton);
}
public String getMeasuringSystem()
{
if (metricRadioButton.isSelected() && !imperialRadioButton.isSelected())
return "Metric";
else if (imperialRadioButton.isSelected() && !metricRadioButton.isSelected())
return "Imperial";
return "No Selection made";
}
// Variables declaration - do not modify
private javax.swing.JButton applyButton;
private javax.swing.JTextField carbsTextField;
private javax.swing.JTextField fatsTextField;
private javax.swing.JRadioButton imperialRadioButton;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JInternalFrame jInternalFrame2;
private javax.swing.JInternalFrame jInternalFrame3;
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.JLabel jLabel7;
private javax.swing.JRadioButton metricRadioButton;
private javax.swing.JTextField proteinsTextField;
// End of variables declaration
}
Edit 2: Here's my class containing the main method
import com.willemdebruyn.macronutrientcalculator.controller.Controller;
import com.willemdebruyn.macronutrientcalculator.model.Model;
import com.willemdebruyn.macronutrientcalculator.view.SettingsView;
import com.willemdebruyn.macronutrientcalculator.view.UserDetailsView;
public class App
{
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(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UserDetailsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
UserDetailsView userDetailsView = new UserDetailsView();
SettingsView settingsView = new SettingsView();
Model model = new Model();
Controller controller = new Controller(userDetailsView, settingsView, model);
userDetailsView.setVisible(true); // SettingsView gets openend from this view
}
}
Edit 3: UserDetailsView.java
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class UserDetailsView extends JFrame
{
private boolean calorieCalculationPerformed;
public UserDetailsView()
{
initComponents();
myInit();
}
/**
* 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()
{
// I removed the generated code, apparently my post exeeded the allowed limit
}
private void myInit()
{
// Disable macros button on startup, will enable again after caloric needs have been calculated
macrosButton.setEnabled(false);
}
private void maleRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When male button is selected, deselect the female radio button
femaleRadioButton.setSelected(false);
}
private void femaleRadioButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// When female button is selected, deselect the male radio button
maleRadioButton.setSelected(false);
}
private void caloriesButtonActionPerformed(java.awt.event.ActionEvent evt)
{
calorieCalculationPerformed = true;
System.out.println("Calories button gets clicked");
if (heightField.getText().isEmpty() || weightField.getText().isEmpty() || ageField.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please fill in all the fields before performing the calculation.");
calorieCalculationPerformed = false;
}
else if ((!maleRadioButton.isSelected() && !femaleRadioButton.isSelected()))
{
JOptionPane.showMessageDialog(this, "Please select your gender.");
calorieCalculationPerformed = false;
}
else if (activityComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your activity level.");
calorieCalculationPerformed = false;
}
else if (goalComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your fitness goal.");
calorieCalculationPerformed = false;
}
// Only when caloric requirements have been calculated will the user be able to calculate macronutrient requirements
if (calorieCalculationPerformed)
macrosButton.setEnabled(true);
else
macrosButton.setEnabled(false);
}
private void macrosButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (heightField.getText().isEmpty() || weightField.getText().isEmpty() || ageField.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please fill in all the fields before performing the calculation.");
}
else if ((!maleRadioButton.isSelected() && !femaleRadioButton.isSelected()))
{
JOptionPane.showMessageDialog(this, "Please select your gender.");
}
else if (activityComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your activity level.");
calorieCalculationPerformed = false;
}
else if (goalComboBox.getSelectedItem().toString() == "<Select>")
{
JOptionPane.showMessageDialog(this, "Please select your fitness goal.");
}
}
private void settingsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
SettingsView settingsView = new SettingsView();
settingsView.setVisible(true);
}
public void addCalorieCalculationListener(ActionListener listenForCalorieButton)
{
caloriesButton.addActionListener(listenForCalorieButton);
}
public void addMacroCalculationListener(ActionListener listenForMacroButton)
{
macrosButton.addActionListener(listenForMacroButton);
}
public double getUserHeight()
{
if (!heightField.getText().isEmpty())
return Double.parseDouble(heightField.getText());
return 0.0;
}
public double getUserWeight()
{
if (!weightField.getText().isEmpty())
return Double.parseDouble(weightField.getText());
return 0.0;
}
public int getUserAge()
{
if (!ageField.getText().isEmpty())
return Integer.parseInt(ageField.getText());
return 0;
}
public String getUserGender()
{
if (femaleRadioButton.isSelected() && !maleRadioButton.isSelected())
{
return "female";
}
else if(maleRadioButton.isSelected() && !femaleRadioButton.isSelected())
{
return "male";
}
else return "No selection made";
}
public String getUserActivityLevel()
{
return (String) activityComboBox.getSelectedItem();
}
public String getUserGoal()
{
return (String) goalComboBox.getSelectedItem();
}
public void displayNutritionalInfo(String message)
{
JOptionPane.showMessageDialog(this, message);
}
public void displayErrorMessage(String errorMessage)
{
JOptionPane.showMessageDialog(this, errorMessage);
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> activityComboBox;
private javax.swing.JTextField ageField;
private javax.swing.JButton caloriesButton;
private javax.swing.JRadioButton femaleRadioButton;
private javax.swing.JComboBox<String> goalComboBox;
private javax.swing.JTextField heightField;
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.JLabel jLabel7;
private javax.swing.JButton macrosButton;
private javax.swing.JRadioButton maleRadioButton;
private javax.swing.JButton settingsButton;
private javax.swing.JTextField weightField;
// End of variables declaration
}

RMI ClassCastException to remote interface

Hi i am having a problem with RMI.
I have this error when i run it.
java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to rmi.converter
This is the interface
converter.java
import java.rmi.RemoteException;
public interface converter {
double CelciusKelvin (double a) throws RemoteException;
double CelciusFahrenheit (double a) throws RemoteException;
double FahrenheitKelvin (double a) throws RemoteException;
double FahrenheitCelcius (double a) throws RemoteException;
double KelvinCelcius (double a) throws RemoteException;
double KelvinFahrenheit (double a) throws RemoteException;
double AtmosPascal (double a) throws RemoteException;
double AtmosPSI (double a) throws RemoteException;
double PascalAtmos (double a) throws RemoteException;
double PascalPSI (double a) throws RemoteException;
double PSIAtmos (double a) throws RemoteException;
double PSIPascal (double a) throws RemoteException;
}
This is the remote method
converterImp.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class converterImp extends UnicastRemoteObject implements converter {
public converterImp() throws RemoteException
{
}
double convert;
#Override
public double CelciusKelvin(double a) throws RemoteException {
convert = a+273.15;
return convert;
}
#Override
public double CelciusFahrenheit(double a) throws RemoteException {
convert = (a*1.8)+32;
return convert;
}
#Override
public double FahrenheitKelvin(double a) throws RemoteException {
convert = (a+459.67)*5/9;
return convert;
}
#Override
public double FahrenheitCelcius(double a) throws RemoteException {
convert=(a-32)/(9/5);
return convert;
}
#Override
public double KelvinCelcius(double a) throws RemoteException {
convert = a - 273.15;
return convert;
}
#Override
public double KelvinFahrenheit(double a) throws RemoteException {
convert=(a-273.15)* 1.8 + 32.00;
return convert;
}
#Override
public double AtmosPascal(double a) throws RemoteException {
convert = a*101325;
return convert;
}
#Override
public double AtmosPSI(double a) throws RemoteException {
convert = a*14.6959488;
return convert;
}
#Override
public double PascalAtmos(double a) throws RemoteException {
convert = a/101325;
return convert;
}
#Override
public double PascalPSI(double a) throws RemoteException {
convert=a*0.000145037;
return convert;
}
#Override
public double PSIAtmos(double a) throws RemoteException {
convert = a*0.0680459639;
return convert;
}
#Override
public double PSIPascal(double a) throws RemoteException {
convert =a*6894.75729;
return convert;
}
}
This is my GUI Client.
package projectrmiclient;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi.converter;
public class ProjectRMIClient extends javax.swing.JFrame {
public ProjectRMIClient() {
initComponents();
}
String num = "";
String str = "";
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jButton21 = new javax.swing.JButton();
jButton22 = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextPane1.setEditable(false);
jScrollPane1.setViewportView(jTextPane1);
jButton1.setText("1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("3");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("4");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("5");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("6");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setText("7");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setText("8");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton9.setText("9");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton10.setText("0");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jButton11.setText("Cancel");
jButton11.setToolTipText("");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jLabel1.setText("Temperature");
jButton12.setText("C~F");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jButton13.setText("F~C");
jButton14.setText("K~C");
jButton15.setText("C~K");
jButton16.setText("F~K");
jButton17.setText("K~F");
jButton18.setText("A~PSI");
jButton19.setText("PSI~A");
jButton20.setText("Pas~A");
jButton21.setText("A~Pas");
jButton22.setText("PSI-Pas");
jButton22.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton22ActionPerformed(evt);
}
});
jButton23.setText("Pas~A");
jLabel2.setText("Pressure");
jLabel3.setText("Result");
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.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton11)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(36, 36, 36)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton23, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton14, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel2))
.addContainerGap(20, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3)
.addComponent(jButton2)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(jButton5)
.addComponent(jButton6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7)
.addComponent(jButton8)
.addComponent(jButton9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton11)
.addComponent(jButton10))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton15)
.addComponent(jButton12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton16)
.addComponent(jButton13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton17)
.addComponent(jButton14))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton18)
.addComponent(jButton21))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton22)
.addComponent(jButton19))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton20)
.addComponent(jButton23))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
str = evt.getActionCommand();
num = num + str;
jTextPane1.setText(num);// TODO add your handling code here:
}
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {
jTextPane1.setText("");
}
private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// fire to localhost port 1099
Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", 1099);
// search for myMessage service
converter impl = (converter) myRegistry.lookup("PTConverter");
if(!jTextPane1.getText().isEmpty())
{
double input = Double.parseDouble(jTextPane1.getText());
// call server's method
double result=impl.CelciusFahrenheit(input);
String answer = result + "Fahrenheit";
jLabel4.setText(answer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #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(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProjectRMIClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ProjectRMIClient().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton21;
private javax.swing.JButton jButton22;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
I developed the GUI using GUI Builder on netbeans.
The problem is when i pressed jButton12. it will show the error as stated.
You appear to have created a copy of your remote interface in a different package for the client. You can't do that. The remote interface has to be the same on both sides: The Same, and that does not include changing its package, or indeed any anything else.

Reading a Array of strings

I've made an application in java using NetBeans IDE and I'm having a problem. It doesn't read the array elements. Here's the code:
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=textbox.getText();
label1.setText(toppings[0]);
label2.setText(toppings[1]);
label3.setText(toppings[2]);
label4.setText(toppings[3]);
}
}
I want to put then each element of the array on the labels(label1,label2,label3,label4) each time I press the button and add a new value for a new element in the vector.
At this time, when I type the value of the first element it sets the value to all labels.
Does anybody have an idea please?
You should create array of JLabel and then fill up the text on them in for loop:
private javax.swing.JLabel label[];
//write these lines within constructor or wherever you are creating your GUI
label = new javax.swing.JLabel[4];//
for (int i = 0 ; i < label.length ;i++)
label[i] = new javax.swing.jLabel();
Then change the buton1ActionPerformed
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=textbox.getText();
if (i < 4)
label[i].setText(toppings[i]);
}
}
EDIT
Here I have put the updated version of your code. Just run it and tell me if it fulfills what you looking for:
public class fereastra extends javax.swing.JFrame {
/**
* Creates new form fereastra
*/
public fereastra() {
initComponents();
buttonGroup1.add(singleplayer);
buttonGroup1.add(twoplayers);
buttonGroup1.add(threeplayers);
buttonGroup1.add(fourplayers);
casutatext.setVisible(true);
panel.setVisible(true);
text.setText("Wellcome! Please choose the number of players!");
}
/**
* 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() {
label = new javax.swing.JLabel[4];//
for (int i = 0 ; i < label.length ;i++)
{label[i] = new javax.swing.JLabel();}
buttonGroup1 = new javax.swing.ButtonGroup();
casutatext = new javax.swing.JTextField();
text = new javax.swing.JLabel();
buton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
panel = new javax.swing.JPanel();
fourplayers = new javax.swing.JRadioButton();
twoplayers = new javax.swing.JRadioButton();
threeplayers = new javax.swing.JRadioButton();
singleplayer = new javax.swing.JRadioButton();
test = new javax.swing.JLabel();
test2 = new javax.swing.JLabel();
test3 = new javax.swing.JLabel();
test4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
casutatext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
casutatextActionPerformed(evt);
}
});
text.setText("Text");
buton1.setText("OK");
buton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buton1ActionPerformed(evt);
}
});
jButton3.setText("Cancel");
fourplayers.setText("4 players");
fourplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fourplayersActionPerformed(evt);
}
});
twoplayers.setText("2 players");
twoplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
twoplayersActionPerformed(evt);
}
});
threeplayers.setText("3 players");
threeplayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
threeplayersActionPerformed(evt);
}
});
singleplayer.setText("Single player");
singleplayer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
singleplayerActionPerformed(evt);
}
});
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(singleplayer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(twoplayers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(threeplayers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fourplayers)
.addContainerGap())
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(singleplayer)
.addComponent(twoplayers)
.addComponent(threeplayers)
.addComponent(fourplayers))
.addContainerGap())
);
test.setText("test");
test2.setText("jLabel1");
test3.setText("jLabel2");
test4.setText("jLabel3");
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(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(label[0])
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(buton1)
.addGap(35, 35, 35)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(label[1])
.addGap(32, 32, 32)
.addComponent(label[2])
.addGap(31, 31, 31)
.addComponent(label[3])))))
.addGap(93, 93, 93))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(text)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buton1)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label[0])
.addComponent(label[1])
.addComponent(label[2])
.addComponent(label[3]))
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>
private void casutatextActionPerformed(java.awt.event.ActionEvent evt) {
}
private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] toppings = new String[20];
toppings[0] = "";
toppings[1] = "";
toppings[2] = "";
toppings[3] = "";
int size = toppings.length;
for (int i=0; i<size; i++){
toppings[i]=casutatext.getText();
if (i < 4)
{label[i].setText(toppings[i]);
}
}
}
private void singleplayerActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=1;
}
private void twoplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=2;
}
private void threeplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=3;
}
private void fourplayersActionPerformed(java.awt.event.ActionEvent evt) {
numarjucatori=4;
}
/**
* #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(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(fereastra.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 fereastra().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buton1;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField casutatext;
private javax.swing.JRadioButton fourplayers;
private javax.swing.JButton jButton3;
private javax.swing.JPanel panel;
private javax.swing.JRadioButton singleplayer;
private javax.swing.JLabel test;
private javax.swing.JLabel test2;
private javax.swing.JLabel test3;
private javax.swing.JLabel test4;
private javax.swing.JLabel text;
private javax.swing.JRadioButton threeplayers;
private javax.swing.JRadioButton twoplayers;
// End of variables declaration
public int numarjucatori;
public String p1="", p2="", p3="", p4="";
private javax.swing.JLabel label[];
}
The first issue I see is that you're trying to set the label text inside of the for loop where you should really be doing it outside:
for(int i = 0; i < toppings.length; i++){
toppings[i] = textbox.getText();
}
label1.setText(toppings[0]);
// etc.

How do I access a string from a class

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.

Categories