JComboBox dynamically updating values - java

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);
}

Related

choosing file with jfilechooser hang the program

i wanted to choose a file from harddisk which contain a matrix.....and i want to save it in an 2d array..but whenever i choose the file,my app hangs and i cant abble to press any other buttons
Here is my sample:
public class Flood extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public static int[][] multi;
public Flood() {
initComponents();
browseB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
switch (fc.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = fc.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
int row = 0;
int col = 0;
while (input.hasNextLine()) {
++row;
Scanner colReader = new Scanner(input.nextLine());
while (colReader.hasNextInt()) {
++col;
}
}
multi = new int[row][col];
input.close();
{
try {
input = new Scanner(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(Flood.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (input.hasNextInt()) {
multi[i][j] = input.nextInt();
}
}
}
break;
}
}
});
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
for(int i=0;i<multi.length;i++)
{
for(int j=0;j<multi[0].length;j++)
{
System.out.println(""+multi[i][j]);
}
}
}
});
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
browseTF = new javax.swing.JTextField();
browseB = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
browseB.setText("Browse");
browseB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseBActionPerformed(evt);
}
});
jLabel1.setText("number of 0 :-");
jLabel2.setText("0");
jLabel3.setText("number of 1 :-");
jLabel4.setText("0");
jButton1.setText("go");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(browseTF, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseB))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(159, 159, 159)
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(browseTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browseB))
.addGap(7, 7, 7)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(176, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void browseBActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Flood.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Flood.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 Flood().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton browseB;
private javax.swing.JTextField browseTF;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
Thanks in Advance
You have an infinite loop here:
while (colReader.hasNextInt()) {
++col;
}
You are not advancing the colReader Scanner at all, so it is forever looking at the first int value on the line.
You can fix it by moving past each int value as you encounter it:
while (colReader.hasNextInt()) {
colReader.nextInt();
++col;
}
In the future, you can solve a problem like this on your own by using a debugger to check where your program is stuck, or, if you’re running on the command line, by forcing Java to print a stack trace for each active thread using Ctrl-Break on Windows or Ctrl-\ (SIGQUIT) on Linux and OS X.

How can I display images and different variables depends on some conditions in this code?

I am learning java and i am pretty new for it. I am trying to create a static profile window using swing. Also, the avatar picture should change depending on user and user information should be read from a text file. This code doesnt give a error but its because of avatarPath. I think the program thinks its non-static.
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo{
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender){
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[];
public static void InfoReader()throws IOException{
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while((s = in.readLine())!= null)
s2 += s + "\n";
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo( s1[0] , s1[1], s1[2] );
permitedUser[1] = new UsersInfo ( s1[3], s1[4], s1[5] );
permitedUser[2] = new UsersInfo ( s1[6], s1[7], s1[8] );
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
public static void ProfilePanel() {
initComponents();
}
public static String AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
return avatarPath;}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " +permitedUser[x].userName+ "\r\nSurname :"+permitedUser[x].userSurname+"\r\nGender :"+permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
Edit: I changed code a bit and it gives error.
Edit2: what I am trying to do is creating users and their profiles. Profile will contain avatar image and 3 variable which are name, surname and gender. I want to display them with respect to users.
I am living problems with this codes;
static void AvatarPic(){
if( x == 0 ){
avatarPath = "\"/Users/hei_cosplay_darker_than_black_by_seras0victoria.jpg\"";
}
else if( x == 1 ){
avatarPath = "\"/Users/lyralei_the_windrunner_by_trungth-d5zhmc1.jpg\"";
}
else if( x == 2 ){
avatarPath = "\"/Users/shingeki_no_kyojin_by_asuka10-d6k762k.jpg\"";
}
}
and
ProfilePanel.AvatarPic();
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource(ProfilePanel.avatarPath)));
There are many problems in your code.
The initComponents() is not a static function .I guess in your static conversion you just replaced every function with public static .And the below is a constructor [I'm sure because it is a Netbeans generated one] and you have modified it also.No need to do that
public static void ProfilePanel() {
initComponents();
}
You can change it back to the way it was
public ProfilePanel() {
initComponents();
}
You'll get a java.lang.NullPointerException at
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(ProfilePanel.AvatarPic())));
because if you are using getResource you just have to specify the filename relative to the package.If you'll be loading from other location,then you have to change it like
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));//file location
Also you have to give the absolute path
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
You'll again get a java.lang.NullPointerException at
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
because you haven't initialized the permitedUser anywhere.So you have to do it like
static UsersInfo permitedUser[]=new UsersInfo[3];
After making those changes and if you run it with 0 then BK201[Code Name Hei] will be on your screen
And Your Edited FullCode[Make change to ImageLocations]
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author B_Ali
*/
public class ProfilePanel extends javax.swing.JFrame {
public static String avatarPath;
public static int x;
public static class UsersInfo {
public int userID;
public String userName;
public String userSurname;
public String userGender;
UsersInfo(String name, String surname, String gender) {
userID = x;
userName = name;
userSurname = surname;
userGender = gender;
}
}
static UsersInfo permitedUser[] = new UsersInfo[3];//change 3
public static void InfoReader() throws IOException {
#SuppressWarnings("UnusedAssignment")
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader("C:\\Users\\B_Ali\\Documents\\NetBeansProjects\\JavaApplication20\\UserInformation.txt"));
String s, s2 = new String();
while ((s = in.readLine()) != null) {
s2 += s + "\n";
}
#SuppressWarnings("UnusedAssignment")
String[] s1 = new String[100];
s1 = s2.split("\\s+");
in.close();
permitedUser[0] = new UsersInfo(s1[0], s1[1], s1[2]);
permitedUser[1] = new UsersInfo(s1[3], s1[4], s1[5]);
permitedUser[2] = new UsersInfo(s1[6], s1[7], s1[8]);
} catch (FileNotFoundException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
//Change 1
public ProfilePanel() {
initComponents();
}
public static String AvatarPic() {
//change 2
if (x == 0) {
avatarPath = "D://hei_cosplay_darker_than_black_by_seras0victoria.jpg";
} else if (x == 1) {
avatarPath = "D://lyralei_the_windrunner_by_trungth-d5zhmc1.jpg";
} else if (x == 2) {
avatarPath = "D://shingeki_no_kyojin_by_asuka10-d6k762k.jpg";
}
return avatarPath;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Avatar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
//Change 2
jLabel1.setIcon(new javax.swing.ImageIcon(ProfilePanel.AvatarPic()));
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 2, true));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jScrollPane2.setName(""); // NOI18N
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
try {
ProfilePanel.InfoReader(); // TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(ProfilePanel.class.getName()).log(Level.SEVERE, null, ex);
}
jTextArea1.setText("Name: " + permitedUser[x].userName + "\r\nSurname :" + permitedUser[x].userSurname + "\r\nGender :" + permitedUser[x].userGender);
jTextArea1.setDragEnabled(true);
jTextArea1.setMaximumSize(new java.awt.Dimension(2147483647, 120));
jTextArea1.setMinimumSize(new java.awt.Dimension(92, 120));
jTextArea1.setPreferredSize(new java.awt.Dimension(164, 120));
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(120, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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
*/
Scanner in = new Scanner(System.in);
x = in.nextInt();
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(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilePanel.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 ProfilePanel().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
public javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
public javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea jTextArea1;
// End of variables declaration
}

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.

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.

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