Problem 1: So basically I am reading from a text file(name, mark1, mark2) for 8 students, I store this in an ArrayList along with a String that is the path for a photo of the user - I then put all the student names in a ComboBox, and when the user selects a name, the two relevant marks and photo then need to be displayed in labels and a panel respectively. Problem is, I have no idea how to retrieve the information when the user selects a name from the ComboBox. My intial thought was to get the selected item and use that, but no idea where to from there...!
Problem 2: When I try to write new information to the text file I get a Nullpointer Excpetion!
//class for reading and writing to the text file
public class FileConnect {
ArrayList<Student> studs = new ArrayList<Student>();
public FileConnect() {
String s;
String a;
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Student\\Desktop\\Marks.txt"));
while ((s = br.readLine()) != null) {
a = br.readLine();
int i = Integer.parseInt(a);
a = br.readLine();
int k = Integer.parseInt(a);
studs.add(new Student(s, "C:\\Users\\Student\\Desktop\\res\\" + s + ".png", i, k));
}
} catch (FileNotFoundException fnf) {
System.out.println("FileNotFoundException: " + fnf);
} catch (IOException ex) {
System.out.println("IOException: " + ex);
}
}
public void addStud(String name, String compLit, String linux) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\Student\\Desktop\\Marks.txt")), true);
out.write(name);
out.write(compLit);
out.write(linux);
} catch (IOException ex) {
System.out.println("IOException: " + ex);
}
}
}
//class for student accessor methods
public class Student {
private String name;
private int compLit;
private int linux;
private String photo;
public Student(String name, String photo, int compLit, int linux) {
this.name = name;
this.photo = photo;
this.compLit = compLit;
this.linux = linux;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getCompLit() {
return this.compLit;
}
public void setCompLit(int compLit) {
this.compLit = compLit;
}
public int getLinux() {
return this.linux;
}
public void setLinux(int linux) {
this.linux = linux;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
//main GUI where it all happens
public class MainGUI extends javax.swing.JFrame {
String name;
int compLit;
int linux;
String photo;
private FileConnect file;
private Student stu;
public MainGUI() {
initComponents();
}
private void menuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void menuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {
Date now = new Date();
JOptionPane.showMessageDialog(this, "Author: Jean van der Walt \n " + now, "About" , JOptionPane.INFORMATION_MESSAGE);
}
**private void cbStudActionPerformed(java.awt.event.ActionEvent evt) {
//user selects item in combo box
//get all the info for the selected item
//display them
//I tried to do something with
//cbStud.getSelected..... but don't think that'll work
}**
**private void btnStudAddActionPerformed(java.awt.event.ActionEvent evt) {
file.addStud(tfStudName.getText(), tfStudCompLit.getText(), tfStudLinux.getText());
//get a Nullpointer exception HERE!!!
}**
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainGUI().setVisible(true);
}
});
}
-----> The text file I'm reading from looks like this:
Anthony Braddock \n
97 \n
87
...... (7 more students)
---------------------------------->
//Entire GUI code
import java.util.Date;
import javax.swing.JOptionPane;
public class MainGUI extends javax.swing.JFrame {
String name;
int compLit;
int linux;
String photo;
private FileConnect file = null;
private Student stu = null;
public MainGUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
lblHeading = new javax.swing.JLabel();
pnlSelectStud = new javax.swing.JPanel();
cbStud = new javax.swing.JComboBox();
pnlMarks = new javax.swing.JPanel();
lblCompLitMark = new javax.swing.JLabel();
lblLinuxMark = new javax.swing.JLabel();
lblCompLitDisplay = new javax.swing.JLabel();
lblLinuxDisplay = new javax.swing.JLabel();
pnlPhoto = new javax.swing.JPanel();
lblPic = new javax.swing.JLabel();
pnlAddStud = new javax.swing.JPanel();
lblStudName = new javax.swing.JLabel();
lblStudCompLit = new javax.swing.JLabel();
lblStudLinux = new javax.swing.JLabel();
tfStudName = new javax.swing.JTextField();
tfStudCompLit = new javax.swing.JTextField();
tfStudLinux = new javax.swing.JTextField();
btnStudAdd = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuItemExit = new javax.swing.JMenuItem();
menuEdit = new javax.swing.JMenu();
menuItemAbout = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblHeading.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
lblHeading.setText("Individual Student Marks");
pnlSelectStud.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select Student", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
cbStud.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Anthony Braddock", "Charl Fourie", "Darren Tiplady", "Jacobus Langenhoven", "Jaun Pierre Reyneke", "Johan van der Merwe", "Johannes Van Eck", "Lodewyk Duminy" }));
cbStud.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbStudActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlSelectStudLayout = new javax.swing.GroupLayout(pnlSelectStud);
pnlSelectStud.setLayout(pnlSelectStudLayout);
pnlSelectStudLayout.setHorizontalGroup(
pnlSelectStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSelectStudLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(cbStud, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
pnlSelectStudLayout.setVerticalGroup(
pnlSelectStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSelectStudLayout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(cbStud, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(66, Short.MAX_VALUE))
);
pnlMarks.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Marks", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
lblCompLitMark.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblCompLitMark.setText("Computer Literacy");
lblLinuxMark.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblLinuxMark.setText("Using Linux");
lblCompLitDisplay.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblCompLitDisplay.setText("UNKNOWN");
lblLinuxDisplay.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblLinuxDisplay.setText("UNKNOWN");
javax.swing.GroupLayout pnlMarksLayout = new javax.swing.GroupLayout(pnlMarks);
pnlMarks.setLayout(pnlMarksLayout);
pnlMarksLayout.setHorizontalGroup(
pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlMarksLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblCompLitMark)
.addComponent(lblLinuxMark))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 164, Short.MAX_VALUE)
.addGroup(pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblCompLitDisplay)
.addComponent(lblLinuxDisplay))
.addGap(18, 18, 18))
);
pnlMarksLayout.setVerticalGroup(
pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlMarksLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCompLitMark)
.addComponent(lblCompLitDisplay))
.addGap(37, 37, 37)
.addGroup(pnlMarksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblLinuxMark)
.addComponent(lblLinuxDisplay))
.addContainerGap(64, Short.MAX_VALUE))
);
pnlPhoto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Photo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
javax.swing.GroupLayout pnlPhotoLayout = new javax.swing.GroupLayout(pnlPhoto);
pnlPhoto.setLayout(pnlPhotoLayout);
pnlPhotoLayout.setHorizontalGroup(
pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPhotoLayout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(lblPic, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
pnlPhotoLayout.setVerticalGroup(
pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPhotoLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(lblPic, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(33, Short.MAX_VALUE))
);
pnlAddStud.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Add your name and marks", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
lblStudName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblStudName.setText("Name");
lblStudCompLit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblStudCompLit.setText("Computer Literacy");
lblStudLinux.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblStudLinux.setText("Using Linux");
tfStudName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
tfStudCompLit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
tfStudLinux.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnStudAdd.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnStudAdd.setText("Add");
btnStudAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStudAddActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlAddStudLayout = new javax.swing.GroupLayout(pnlAddStud);
pnlAddStud.setLayout(pnlAddStudLayout);
pnlAddStudLayout.setHorizontalGroup(
pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlAddStudLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblStudName)
.addComponent(lblStudCompLit)
.addComponent(lblStudLinux))
.addGap(14, 14, 14)
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlAddStudLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(tfStudName, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pnlAddStudLayout.createSequentialGroup()
.addGap(166, 166, 166)
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tfStudLinux, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(tfStudCompLit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)))))
.addComponent(btnStudAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pnlAddStudLayout.setVerticalGroup(
pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlAddStudLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblStudName)
.addComponent(tfStudName, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblStudCompLit)
.addComponent(tfStudCompLit, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(pnlAddStudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblStudLinux)
.addComponent(tfStudLinux, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addComponent(btnStudAdd, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE))
);
menuFile.setText("File");
menuItemExit.setText("Exit");
menuItemExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItemExitActionPerformed(evt);
}
});
menuFile.add(menuItemExit);
menuBar.add(menuFile);
menuEdit.setText("Edit");
menuItemAbout.setText("About");
menuItemAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItemAboutActionPerformed(evt);
}
});
menuEdit.add(menuItemAbout);
menuBar.add(menuEdit);
setJMenuBar(menuBar);
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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlPhoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlSelectStud, 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.LEADING)
.addComponent(pnlMarks, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlAddStud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(26, 26, 26))
.addGroup(layout.createSequentialGroup()
.addGap(216, 216, 216)
.addComponent(lblHeading)
.addContainerGap(250, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(lblHeading, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(pnlMarks, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlSelectStud, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(pnlAddStud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlPhoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(19, 19, 19))
);
pack();
}// </editor-fold>
private void menuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void menuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {
Date now = new Date();
JOptionPane.showMessageDialog(this, "Author: Jean van der Walt \n " + now, "About" , JOptionPane.INFORMATION_MESSAGE);
}
private void cbStudActionPerformed(java.awt.event.ActionEvent evt) {
//user selects item in combo box
//get all the info for the selected item
//display them
}
private void btnStudAddActionPerformed(java.awt.event.ActionEvent evt) {
file.addStud(tfStudName.getText(), tfStudCompLit.getText(), tfStudLinux.getText());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnStudAdd;
private javax.swing.JComboBox cbStud;
private javax.swing.JLabel lblCompLitDisplay;
private javax.swing.JLabel lblCompLitMark;
private javax.swing.JLabel lblHeading;
private javax.swing.JLabel lblLinuxDisplay;
private javax.swing.JLabel lblLinuxMark;
private javax.swing.JLabel lblPic;
private javax.swing.JLabel lblStudCompLit;
private javax.swing.JLabel lblStudLinux;
private javax.swing.JLabel lblStudName;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenu menuEdit;
private javax.swing.JMenu menuFile;
private javax.swing.JMenuItem menuItemAbout;
private javax.swing.JMenuItem menuItemExit;
private javax.swing.JPanel pnlAddStud;
private javax.swing.JPanel pnlMarks;
private javax.swing.JPanel pnlPhoto;
private javax.swing.JPanel pnlSelectStud;
private javax.swing.JTextField tfStudCompLit;
private javax.swing.JTextField tfStudLinux;
private javax.swing.JTextField tfStudName;
// End of variables declaration//GEN-END:variables
}
Problem 1. it's kind of unclear what you have since you seem to be missing some of the gui code, but generally, i would store a Map<String, Student> which maps each "Student name" to their "Student instance" and use that to find the Student when chosen by the combo box (assuming you are showing the student names and that the names are unique).
Problem 2. You don't ever seem to be initializing file.
Related
If I click a row(JTABLE), it must display the specific values back to the textfields/combobox/radiobutton/spinner. But in my case, it's just hard to retrieve the values back to the RADIO BUTTON and SPINNER.
package coffeeshop;
import java.awt.HeadlessException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
public class coffeeframe extends javax.swing.JFrame {
public coffeeframe() {
initComponents();
ArrayList coffeeArray = new ArrayList();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
btnAdd = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
coffeeType = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
coffeeName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
coffeePrice = new javax.swing.JTextField();
quanOrder = new javax.swing.JSpinner();
jLabel5 = new javax.swing.JLabel();
dinein = new javax.swing.JRadioButton();
togo = new javax.swing.JRadioButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton1.setText("jButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 51));
table.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
table.setForeground(new java.awt.Color(204, 0, 51));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer", "Coffee Type", "Coffee Name", "Price", "Order Mode", "Quantity", "Total"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table.setGridColor(new java.awt.Color(0, 102, 102));
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(table);
btnAdd.setBackground(new java.awt.Color(204, 255, 204));
btnAdd.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
btnAdd.setForeground(new java.awt.Color(102, 102, 102));
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/Add-icon (1).png"))); // NOI18N
btnAdd.setText("ADD ORDER");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
jPanel1.setBackground(java.awt.Color.gray);
jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel1.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Customer");
name.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
name.setForeground(new java.awt.Color(51, 51, 51));
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
coffeeType.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
coffeeType.setForeground(new java.awt.Color(102, 102, 102));
coffeeType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose", "Esprezo $20", "Green Tea Frappe $75", "Barako $22", "Black Coffee $28" }));
coffeeType.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
coffeeTypeItemStateChanged(evt);
}
});
coffeeType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeTypeActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Coffee name");
coffeeName.setEditable(false);
coffeeName.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeeName.setForeground(new java.awt.Color(102, 102, 102));
coffeeName.setText(" ");
coffeeName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
coffeeNameActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Coffee Type");
jLabel4.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Coffee price");
coffeePrice.setEditable(false);
coffeePrice.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
coffeePrice.setForeground(new java.awt.Color(102, 102, 102));
coffeePrice.setText(" ");
quanOrder.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
quanOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1));
jLabel5.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Quantity");
buttonGroup1.add(dinein);
dinein.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
dinein.setForeground(new java.awt.Color(255, 255, 255));
dinein.setSelected(true);
dinein.setText("Dine-In");
dinein.setBorder(null);
dinein.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dineinActionPerformed(evt);
}
});
buttonGroup1.add(togo);
togo.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
togo.setForeground(new java.awt.Color(255, 255, 255));
togo.setText("To-Go");
togo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
togoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name)
.addComponent(coffeeType, 0, 163, Short.MAX_VALUE))
.addGap(112, 112, 112))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(togo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(coffeePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeType, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(coffeePrice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(togo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jButton2.setBackground(new java.awt.Color(255, 204, 204));
jButton2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton2.setForeground(new java.awt.Color(102, 102, 102));
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/edit-icon.png"))); // NOI18N
jButton2.setText("EDIT ORDER");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(255, 51, 51));
jButton3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
jButton3.setForeground(new java.awt.Color(239, 234, 234));
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/trash-icon.png"))); // NOI18N
jButton3.setText(" ");
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 201, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, 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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.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())
);
pack();
}// </editor-fold>
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
try{
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
DefaultTableModel model = (DefaultTableModel)table.getModel();
Coffee coffee = new Coffee(name.getText(),coffeeType.getSelectedItem().toString(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue(),total);
coffeeArray.add(coffee);
if(name.getText().trim().isEmpty()){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else if(buttonGroup1.getSelection().getActionCommand()== null){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}else{
String customerName = name.getText();
String cofType = coffeeType.getSelectedItem().toString();
String cofName = coffeeName.getText();
int price = Integer.parseInt(coffeePrice.getText());
String OrderMode= buttonGroup1.getSelection().getActionCommand();
int quantity = (Integer)quanOrder.getValue();
Object[] rowCoffee = {customerName,cofType,cofName,price,OrderMode,quantity,total};
model.addRow(rowCoffee);
}
}catch(NumberFormatException | HeadlessException e){
JOptionPane.showMessageDialog(null,"Complete the order details!");
}
}
private void coffeeTypeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str_coffee_name = (String)coffeeType.getSelectedItem();
String input_coffee_name = str_coffee_name.replaceAll("[^a-zA-Z]","");
coffeeName.setText(input_coffee_name);
String str_coffee_price = (String)coffeeType.getSelectedItem();
String input_coffee_price = str_coffee_price.replaceAll("[^0-9]","");
coffeePrice.setText(input_coffee_price);
}
private void coffeeNameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void togoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
togo.setActionCommand("TO-GO");
}
private void dineinActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dinein.setActionCommand("DINE-IN");
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void coffeeTypeItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)table.getModel();
int i = table.getSelectedRow();
int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
if(i >= 0)
{
model.setValueAt(name.getText(), i, 0);
model.setValueAt(coffeeType.getSelectedItem(), i, 1);
model.setValueAt(coffeeName.getText(), i, 2);
model.setValueAt(Integer.parseInt(coffeePrice.getText()), i, 3);
model.setValueAt(buttonGroup1.getSelection().getActionCommand(), i, 4);
model.setValueAt((Integer)quanOrder.getValue(), i, 5);
model.setValueAt(total, i, 6);
}
else{
System.out.println("Update Error");
}
}
private void tableMouseClicked(java.awt.event.MouseEvent evt) {
try{
DefaultTableModel model = (DefaultTableModel)table.getModel();
int row = table.getSelectedRow();
name.setText(model.getValueAt(row, 0).toString());
coffeeType.setSelectedItem(table.getValueAt(row, 1).toString());
coffeeName.setText(model.getValueAt(row, 2).toString());
coffeePrice.setText(model.getValueAt(row, 3).toString());
quanOrder.setValue(model.getValueAt(row, 5).toString());
}catch(Exception e){
}
}
/**
* #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(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(coffeeframe.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 coffeeframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAdd;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField coffeeName;
private javax.swing.JTextField coffeePrice;
private javax.swing.JComboBox<String> coffeeType;
private javax.swing.JRadioButton dinein;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
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.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField name;
private javax.swing.JSpinner quanOrder;
private javax.swing.JTable table;
private javax.swing.JRadioButton togo;
// End of variables declaration
ArrayList<Coffee> coffeeArray = new ArrayList<>();
int length = 0;
}
How to change the values of spinner and radio button
The spinner should be easily settable by calling its setValue(...) method, and passing in the number from the selected table row item.
For the JRadioButtons, probably the easiest solution is to use a Map that maps the selection to its radio button, and then using this map to get a reference to the proper JRadioButton, and calling setSelected(true) on it.
For an example, and for an example of a Minimal, Complete, and Verifiable example, please have a look at:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.EnumMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class CoffeeMcve extends JPanel {
private CoffeeTableModel tableModel = new CoffeeTableModel();
private JTable table = new JTable(tableModel);
private Map<OrderMode, ButtonModel> modeButtonMap = new EnumMap<>(OrderMode.class);
private JSpinner quantSpinner = new JSpinner(new SpinnerNumberModel(1, 0, 20, 1));
private JTextField nameTField = new JTextField(10);
private ButtonGroup modeBtnGroup = new ButtonGroup();
public CoffeeMcve() {
JPanel modePanel = new JPanel();
modePanel.setBorder(BorderFactory.createTitledBorder("Order Mode"));
for (OrderMode mode : OrderMode.values()) {
JRadioButton rBtn = new JRadioButton(mode.getText());
rBtn.setActionCommand(mode.toString());
modeBtnGroup.add(rBtn);
modePanel.add(rBtn);
modeButtonMap.put(mode, rBtn.getModel());
}
JPanel orderPanel = new JPanel();
orderPanel.add(new JLabel("Name:"));
orderPanel.add(nameTField);
orderPanel.add(new JLabel("Quantity:"));
orderPanel.add(quantSpinner);
orderPanel.add(modePanel);
orderPanel.add(new JButton(new AddAction("Add", KeyEvent.VK_A)));
table.getColumnModel().getColumn(2).setCellRenderer(new OrderModeColumnRenderer());
JScrollPane scrollPane = new JScrollPane(table);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(orderPanel, BorderLayout.PAGE_END);
table.getSelectionModel().addListSelectionListener(new MyTableListener());
}
public void setOrderData(CoffeeOrder2 order) {
nameTField.setText(order.getName());
quantSpinner.setValue(order.getQuant());
ButtonModel btnModel = modeButtonMap.get(order.getOrderMode());
modeBtnGroup.setSelected(btnModel, true);
}
private class MyTableListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int index = table.getSelectedRow();
CoffeeOrder2 order = tableModel.getRow(index);
setOrderData(order);
}
}
}
private class OrderModeColumnRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null && value instanceof OrderMode) {
value = ((OrderMode) value).getText();
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
private class AddAction extends AbstractAction {
public AddAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String name = nameTField.getText();
int quant = (int) quantSpinner.getValue();
ButtonModel model = modeBtnGroup.getSelection();
if (model != null) {
String actionCommand = model.getActionCommand();
OrderMode orderMode = OrderMode.valueOf(actionCommand);
CoffeeOrder2 coffeeOrder2 = new CoffeeOrder2(name, quant, orderMode);
tableModel.addRow(coffeeOrder2);
}
}
}
private static void createAndShowGui() {
CoffeeMcve mainPanel = new CoffeeMcve();
JFrame frame = new JFrame("CoffeeMcve");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class CoffeeTableModel extends DefaultTableModel {
public static final String[] TITLES = {"Name", "Quantity", "Order Mode"};
public CoffeeTableModel() {
super(TITLES, 0);
}
public void addRow(CoffeeOrder2 coffee2) {
Vector<Object> rowData = new Vector<>();
rowData.add(coffee2.getName());
rowData.add(coffee2.getQuant());
rowData.add(coffee2.getOrderMode());
super.addRow(rowData);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object value = getValueAt(0, columnIndex);
if (value == null) {
return super.getColumnClass(columnIndex);
} else {
return value.getClass();
}
}
public CoffeeOrder2 getRow(int rowIndex) {
if (rowIndex < 0 || rowIndex >= getRowCount()) {
String text = "For rowIndex: " + rowIndex;
throw new IllegalArgumentException(text);
}
String name = getValueAt(rowIndex, 0).toString();
int quant = (int) getValueAt(rowIndex, 1);
OrderMode orderMode = (OrderMode) getValueAt(rowIndex, 2);
return new CoffeeOrder2(name, quant, orderMode);
}
}
class CoffeeOrder2 {
private String name;
private int quant;
private OrderMode orderMode;
public CoffeeOrder2(String name, int quant, OrderMode orderMode) {
this.name = name;
this.quant = quant;
this.orderMode = orderMode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuant() {
return quant;
}
public void setQuant(int quant) {
this.quant = quant;
}
public OrderMode getOrderMode() {
return orderMode;
}
public void setOrderMode(OrderMode orderMode) {
this.orderMode = orderMode;
}
}
enum OrderMode {
HERE("Here"), TO_GO("To Go");
private String text;
private OrderMode(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
This is my code below
package javaapplication1;
/*
This is the registration class
This is the class that has the code to
Add a new employee
This is by entering such information as their
Username
Password Business Name
Type of Business
Email
Contact Number
Address
Employee Status
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.Random;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class Registration extends javax.swing.JFrame {
public static Random rand = new Random((new Date()).getTime());
Statement stmt;
public Registration() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
EnterButton = new javax.swing.JButton();
ClearButton = new javax.swing.JButton();
UserNameLabel = new javax.swing.JLabel();
ContactNumberLabel = new javax.swing.JLabel();
AddressLabel = new javax.swing.JLabel();
EmailLabel = new javax.swing.JLabel();
UsernameTextField = new javax.swing.JTextField();
BusinessNameTextField = new javax.swing.JTextField();
RegistrationLabel = new javax.swing.JLabel();
PasswordLabel = new javax.swing.JLabel();
BusinessNameLabel = new javax.swing.JLabel();
TypeOfBusinessLabel = new javax.swing.JLabel();
EmailTextField = new javax.swing.JTextField();
ContactNumberTextField = new javax.swing.JTextField();
AddressTextField = new javax.swing.JTextField();
PasswordTextField = new javax.swing.JPasswordField();
BusinessTypeComboBox = new javax.swing.JComboBox<>();
EmployedLabel = new javax.swing.JLabel();
YesRadioButton = new javax.swing.JRadioButton();
NoRadioButton = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setMinimumSize(new java.awt.Dimension(93, 432));
EnterButton.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
EnterButton.setText("Enter");
EnterButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnterButtonActionPerformed(evt);
}
});
ClearButton.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
ClearButton.setText("Clear");
ClearButton.setToolTipText("");
ClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearButtonActionPerformed(evt);
}
});
UserNameLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
UserNameLabel.setLabelFor(UsernameTextField);
UserNameLabel.setText("UserName");
ContactNumberLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
ContactNumberLabel.setText("Contact Number");
AddressLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
AddressLabel.setLabelFor(BusinessNameTextField);
AddressLabel.setText("Address");
AddressLabel.setToolTipText("");
EmailLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
EmailLabel.setText("Email");
UsernameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsernameTextFieldActionPerformed(evt);
}
});
BusinessNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BusinessNameTextFieldActionPerformed(evt);
}
});
RegistrationLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
RegistrationLabel.setText("Employee Registration");
RegistrationLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
RegistrationLabel.setMaximumSize(new java.awt.Dimension(100, 25));
PasswordLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PasswordLabel.setText("Password");
BusinessNameLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
BusinessNameLabel.setText("Business Name");
TypeOfBusinessLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
TypeOfBusinessLabel.setText("Type of Business");
EmailTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmailTextFieldActionPerformed(evt);
}
});
ContactNumberTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ContactNumberTextFieldActionPerformed(evt);
}
});
AddressTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddressTextFieldActionPerformed(evt);
}
});
BusinessTypeComboBox.setEditable(true);
BusinessTypeComboBox.setMaximumRowCount(30);
BusinessTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "", "Laundromat", "Computer Shop" }));
BusinessTypeComboBox.setMinimumSize(new java.awt.Dimension(95, 20));
BusinessTypeComboBox.setName(""); // NOI18N
BusinessTypeComboBox.setPreferredSize(new java.awt.Dimension(900, 900));
BusinessTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BusinessTypeComboBoxActionPerformed(evt);
}
});
EmployedLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
EmployedLabel.setText("Employed");
YesRadioButton.setText("Yes");
YesRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
YesRadioButtonActionPerformed(evt);
}
});
NoRadioButton.setText("No");
NoRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NoRadioButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(278, 278, 278)
.addComponent(RegistrationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(189, 189, 189)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BusinessNameLabel)
.addComponent(PasswordLabel)
.addComponent(UserNameLabel)
.addComponent(TypeOfBusinessLabel)
.addComponent(EmailLabel)
.addComponent(ContactNumberLabel)
.addComponent(AddressLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmployedLabel))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BusinessTypeComboBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ContactNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(BusinessNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(PasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(UsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(YesRadioButton)
.addGap(18, 18, 18)
.addComponent(NoRadioButton))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ClearButton)
.addComponent(EnterButton))
.addGap(177, 177, 177)))
.addGap(0, 210, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(RegistrationLabel, 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.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(UsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(16, 16, 16)
.addComponent(BusinessNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(BusinessTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(UserNameLabel)
.addGap(16, 16, 16)
.addComponent(PasswordLabel)
.addGap(18, 18, 18)
.addComponent(BusinessNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(TypeOfBusinessLabel)))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmailLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ContactNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ContactNumberLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AddressLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmployedLabel)
.addComponent(YesRadioButton)
.addComponent(NoRadioButton))
.addGap(18, 18, 18)
.addComponent(EnterButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ClearButton)
.addContainerGap(79, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static String encrypt(String passwordToHash){
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return generatedPassword;
}
private void UsernameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// This is the text field for the username
}
private void BusinessNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// This is the text field for the type of business
}
private void EnterButtonActionPerformed(java.awt.event.ActionEvent evt) {
/* This is the enter button.
When this is pressed the customers details are entered in the database
*/
String url = "jdbc:derby://localhost:1527/Customers";
String username = "username";
String password = "password";
String encString = encrypt(PasswordTextField.getText());
try {
Connection conn = DriverManager.getConnection(url, username, password);
if (conn !=null){
System.out.println("Connected");
String sql = "INSERT INTO Registration (username, Password, businessName, typeofBusiness, email, contactnumber, address, Employed) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, UsernameTextField.getText());
statement.setString(2, encString = (PasswordTextField.getText()));
statement.setString(3, BusinessNameTextField.getText());
statement.setString(4, BusinessTypeComboBox.getSelectedItem().toString());
statement.setString(5, EmailTextField.getText());
statement.setString(6, ContactNumberTextField.getText());
statement.setString(7, AddressTextField.getText());
statement.setString(8, EmployStatus);
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, "A new user has been added successfully");
}
}
} catch (SQLException ex){
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, "ERROR!");
}
}
private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt) {
/*This is the Clear button
When it is pressed it will clear all the text fields
*/
UsernameTextField.setText("");
PasswordTextField.setText("");
BusinessNameTextField.setText("");
EmailTextField.setText("");
ContactNumberTextField.setText("");
AddressTextField.setText("");
}
private void EmailTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// This is the email
}
private void ContactNumberTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// This is the customers contact number
}
private void AddressTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// This is the customers address
}
private void BusinessTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
/* This the drop down list for the type of business
The user can choose a company already on the lisr or they can enter a new company
*/
}
private void YesRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {
// This is the yes radio button for if the employee is still employed
EmployStatus = "Yes";
}
private void NoRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {
// This is the no radio button for if the employee is still employed
EmployStatus = "No";
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Registration().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel AddressLabel;
private javax.swing.JTextField AddressTextField;
private javax.swing.JLabel BusinessNameLabel;
private javax.swing.JTextField BusinessNameTextField;
private javax.swing.JComboBox<String> BusinessTypeComboBox;
private javax.swing.JButton ClearButton;
private javax.swing.JLabel ContactNumberLabel;
private javax.swing.JTextField ContactNumberTextField;
private javax.swing.JLabel EmailLabel;
private javax.swing.JTextField EmailTextField;
private javax.swing.JLabel EmployedLabel;
private javax.swing.JButton EnterButton;
private javax.swing.JRadioButton NoRadioButton;
private javax.swing.JLabel PasswordLabel;
private javax.swing.JPasswordField PasswordTextField;
private javax.swing.JLabel RegistrationLabel;
private javax.swing.JLabel TypeOfBusinessLabel;
private javax.swing.JLabel UserNameLabel;
private javax.swing.JTextField UsernameTextField;
private javax.swing.JRadioButton YesRadioButton;
// End of variables declaration
private String EmployStatus;
}
This will encrypt the password
public static String encrypt(String passwordToHash){
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return generatedPassword;
}
But I don't know how to apply this to the password that the user enters so that when the password is entered into the database here
String sql = "INSERT INTO Registration (username, Password, businessName, typeofBusiness, email, contactnumber, address, Employed) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, UsernameTextField.getText());
statement.setString(2, encString = (PasswordTextField.getText()));
statement.setString(3, BusinessNameTextField.getText());
statement.setString(4, BusinessTypeComboBox.getSelectedItem().toString());
statement.setString(5, EmailTextField.getText());
statement.setString(6, ContactNumberTextField.getText());
statement.setString(7, AddressTextField.getText());
statement.setString(8, EmployStatus);
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, "A new user has been added successfully");
}
}
The password stored would be the encrypted password
Instead use an itererated HMAC, functions that do this include PBKDF2, password_hash, bcrypt, etc.
Notes:
Do not use Random with the time as a seed, to get a seed, use the cryptographic CPRNG: java.security.SecureRandom, it does not need to be seeded.
Do not use MD5 (attackers love it).
Hasing is not encryption, it is a one-way function, encryption is a two-way (it can be decrypted).
statement.setString(2, encrypt(PasswordTextField.getText()));
Can you call Registration.encrypt(PasswordTextField.getText()) when setting the strings?
Also, nitpick: the password is (and should be) being hashed, not encrypted. Encryption implies it can be decrypted.
I am creating a 2 player game in which clients receive 2 Strings from the server and have to respond with a String of their own. The internal processing is irrelevant here. The main thing is, whenever I send data from server, one of the clients ends up showing a NullPointerException for a setText() function. I am baffled as nobody else at my university knows the reason for that. Please help me solve this issue.
Here is the code (the IDE is NetBeans 7.3.1):
Server
public class TCPServer {
public static void main(String argv[]) throws Exception {
String childWord, childWord2;
Trie1 obj = new Trie1();
obj.loadTrie();
ServerSocket welcomeSocket = new ServerSocket(6759);
ServerSocket welcomeSocket2 = new ServerSocket(6559);
//BufferedReader dd = new BufferedReader(new InputStreamReader(System.in));
String parentWord;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
Socket connectionSocket2 = welcomeSocket2.accept();
//parentWord = dd.readLine();
parentWord = GlobalStuff.word;
System.out.println("word: "+parentWord);
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromClient2 =
new BufferedReader(new InputStreamReader(connectionSocket2.getInputStream()));
DataOutputStream outToClient2 =
new DataOutputStream(connectionSocket2.getOutputStream());
outToClient.writeBytes(parentWord + "\n");
outToClient2.writeBytes(parentWord + "\n");
outToClient.writeBytes(GlobalStuff.sentence + "\n");
outToClient2.writeBytes(GlobalStuff.sentence + "\n");
childWord = inFromClient.readLine();
childWord2 = inFromClient2.readLine();
/*System.out.println(childWord);
System.out.println(childWord2);*/
//System.out.println(clientSentence);
if (childWord.equals(childWord2)) {
System.out.println("The suggestions match!!");
obj.Trie1Main(parentWord, childWord);
} else {
System.out.println("The suggestions DO NOT match...the users entered:");
System.out.println(childWord+" and "+childWord2);
}
}
}
}
Client:
package clientserver;
import markI.*;
import sessionmanager.*;
import java.io.*;
import java.net.*;
public class Player1 extends javax.swing.JFrame {
private static Socket clientSocket;
private static BufferedReader inFromUser;
private static DataOutputStream outToServer;
private static BufferedReader inFromServer;
private static String modifiedSentence;
private static String modifiedWord;
/**
* Creates new form TestFrameOne
*/
public Player1() {
initComponents();
}
//user defined
private void initComponents() {
tlabel = new javax.swing.JLabel();
ilabel = new javax.swing.JLabel();
totalScore = new javax.swing.JLabel();
wordtf = new javax.swing.JTextField();
submit = new javax.swing.JButton();
close = new javax.swing.JButton();
round = new javax.swing.JLabel();
opponent = new javax.swing.JLabel();
hword = new javax.swing.JLabel();
timeLeft = new javax.swing.JLabel();
points = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
sentenceArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tlabel.setFont(new java.awt.Font("Trebuchet MS", 1, 24)); // NOI18N
tlabel.setForeground(new java.awt.Color(51, 0, 255));
tlabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
tlabel.setText("WORD KING");
ilabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
ilabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/markI/crown_low.png"))); // NOI18N
totalScore.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
totalScore.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
totalScore.setText("0");
totalScore.setBorder(javax.swing.BorderFactory.createTitledBorder("Net Score"));
wordtf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
wordtf.setBorder(javax.swing.BorderFactory.createTitledBorder("Alternate Word"));
submit.setBackground(new java.awt.Color(102, 0, 255));
submit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
submit.setText("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
});
close.setText("X");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
round.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
round.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
round.setText("0");
round.setBorder(javax.swing.BorderFactory.createTitledBorder("Round"));
opponent.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
opponent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/markI/face_low.jpg"))); // NOI18N
opponent.setBorder(javax.swing.BorderFactory.createTitledBorder("OPPONENT"));
hword.setFont(new java.awt.Font("Trebuchet MS", 1, 18)); // NOI18N
hword.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hword.setBorder(javax.swing.BorderFactory.createTitledBorder("Highlighted Word"));
timeLeft.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
timeLeft.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
timeLeft.setText("30");
timeLeft.setBorder(javax.swing.BorderFactory.createTitledBorder("Time"));
points.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
points.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
points.setText("0");
points.setBorder(javax.swing.BorderFactory.createTitledBorder("Points"));
jButton1.setBackground(new java.awt.Color(102, 0, 255));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Leave Game");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
sentenceArea.setColumns(20);
sentenceArea.setRows(5);
sentenceArea.setText("The quick brown fox jumps over a lazy dog.");
sentenceArea.setBorder(javax.swing.BorderFactory.createTitledBorder("Sentence"));
jScrollPane1.setViewportView(sentenceArea);
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)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(hword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(wordtf, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(ilabel)
.addComponent(tlabel))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(points, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(timeLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(round, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(totalScore, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(opponent)
.addGap(18, 18, 18)
.addComponent(close)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(opponent))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(close)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ilabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tlabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hword, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(round)
.addComponent(totalScore))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(points)
.addComponent(timeLeft)
.addComponent(wordtf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void submitActionPerformed(java.awt.event.ActionEvent evt) {
//wordtf.setText(modifiedSentence);
try {
String sentence = wordtf.getText();
System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
clientSocket.close();
} catch (Exception e) {
System.out.println("Some error through submit button.\n" + e.getMessage());
}
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(WIDTH); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
sessionmanager.WelcomePage.main(null);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws Exception {
/* 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(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestFrameOne.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 Player1().setVisible(true);
}
});
//Start clientserver
inFromUser = new BufferedReader(new InputStreamReader(System.in));
clientSocket = new Socket("172.16.30.183", 6759);
//clientSocket = new Socket("172.16.38.156", 6759);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
modifiedWord = inFromServer.readLine();
System.out.println("FROM SERVER: word " + modifiedWord);
hword.setText(modifiedWord);
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: sentence " + modifiedSentence);
sentenceArea.setText(modifiedSentence);
//End clientserver
}
// Variables declaration - do not modify
private javax.swing.JButton close;
public static javax.swing.JLabel hword;
private javax.swing.JLabel ilabel;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel opponent;
private javax.swing.JLabel points;
private javax.swing.JLabel round;
public static javax.swing.JTextArea sentenceArea;
private javax.swing.JButton submit;
private javax.swing.JLabel timeLeft;
private javax.swing.JLabel tlabel;
private javax.swing.JLabel totalScore;
public static javax.swing.JTextField wordtf;
// End of variables declaration
}
This is the Exception
This is supposed to be the output if the client runs correctly
Line 272 in the error message is hword.setText(modifiedWord)
So this means that hword is null and you have to ensure it has been initialised before you call this method.
Any update to the GUI should be performed on the GUI thread in any case. I suggest you submit a task to perform the update. This way it should be initialised by the time you use it.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
hword.setText(modifiedWord);
}
});
What you should be doing though, is calling this method on the Player1 instance instead of setting a static field. You really shouldn't be initialising static fields in a constructor.
Player1 player1 = new Player1();
EventQueue.invokeLater(() -> player1.setVisible(true));
EventQueue.invokeLater(() -> player1.setHwordText(modifiedWord));
This way you don't need the static fields.
I'm making a hangman game and this is my current code:
//Declaring the array
String [] WordList = {"anonymous", "tolerate", "appreciation", "commissioner", "harm", "flexibility", "instructional", "scramble", "casino", "tumor"};
// Getting a random word for the game
int num = ((int)Math.ceil(Math.random()*(WordList.length)));
String word = WordList[num];
// The puzzle to be displayed for the user to guess
int letters = word.length();
String hiddenWord = "";
for (int i=0; i<letters; i++){
hiddenWord+="-";
}
At the for loop, I get an error saying 'illegal start of type, cannot find symbol: class i'. 'i' is supposed to be an integer, which I've already declared, so I'm not sure why it's asking for a class.
There's also another error saying, 'identifier expected' and that there's a missing >. As my < is meant to be used as comparison (and not as a declaration or identifier), I don't understand this error.
For clarification, I should add that this is a desktop application in netbeans. The code is located after the line:
public class HangmanGameView extends FrameView {
Most of the rest of my code will be located within the actionPerformed code for my buttons. I need to be able to access the word and hiddenWord variables from within the code for the buttons, which is why I've put them here. I'm not positive if that's the problem as of yet. I'm also not sure where to put the code otherwise; there is no main method as far as I can see.
Edit: I hadn't posted the complete code because this is all I've done for now; the rest is all auto-generated by NetBeans, and I thought it wouldn't be relevant. But here it is:
/*
* HangmanGameView.java
*/
package hangmangame;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* The application's main frame.
*/
public class HangmanGameView extends FrameView {
//Declaring the array
String [] WordList = {"anonymous", "tolerate", "appreciation", "commissioner", "harm", "flexibility", "instructional", "scramble", "casino", "tumor"};
// Getting a random word for the game
int num = ((int)Math.ceil(Math.random()*(WordList.length)));
String word = WordList[num];
// The puzzle to be displayed for the user to guess
int letters = word.length();
String hiddenWord = "";
for (int i=0; i<letters; i++){
hiddenWord+="-";
}
public HangmanGameView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
#Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = HangmanGameApp.getApplication().getMainFrame();
aboutBox = new HangmanGameAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
HangmanGameApp.getApplication().show(aboutBox);
}
/** 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() {
mainPanel = new javax.swing.JPanel();
titleLabel = new javax.swing.JLabel();
startButton = new javax.swing.JButton();
guesswordOutput = new javax.swing.JLabel();
guessLabel = new javax.swing.JLabel();
guessInput = new javax.swing.JTextField();
guessButton = new javax.swing.JButton();
picLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
gameOutput = new javax.swing.JTextArea();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(hangmangame.HangmanGameApp.class).getContext().getResourceMap(HangmanGameView.class);
mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
mainPanel.setName("mainPanel"); // NOI18N
titleLabel.setFont(titleLabel.getFont().deriveFont(titleLabel.getFont().getSize()+19f));
titleLabel.setForeground(resourceMap.getColor("titleLabel.foreground")); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText(resourceMap.getString("titleLabel.text")); // NOI18N
titleLabel.setName("titleLabel"); // NOI18N
startButton.setFont(startButton.getFont().deriveFont(startButton.getFont().getStyle() & ~java.awt.Font.BOLD, startButton.getFont().getSize()+5));
startButton.setForeground(resourceMap.getColor("startButton.foreground")); // NOI18N
startButton.setText(resourceMap.getString("startButton.text")); // NOI18N
startButton.setToolTipText(resourceMap.getString("startButton.toolTipText")); // NOI18N
startButton.setName("startButton"); // NOI18N
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
guesswordOutput.setText(resourceMap.getString("guesswordOutput.text")); // NOI18N
guesswordOutput.setName("guesswordOutput"); // NOI18N
guessLabel.setFont(resourceMap.getFont("guessLabel.font")); // NOI18N
guessLabel.setText(resourceMap.getString("guessLabel.text")); // NOI18N
guessLabel.setName("guessLabel"); // NOI18N
guessInput.setBackground(resourceMap.getColor("guessInput.background")); // NOI18N
guessInput.setFont(resourceMap.getFont("guessInput.font")); // NOI18N
guessInput.setText(resourceMap.getString("guessInput.text")); // NOI18N
guessInput.setToolTipText(resourceMap.getString("guessInput.toolTipText")); // NOI18N
guessInput.setName("guessInput"); // NOI18N
guessButton.setFont(resourceMap.getFont("guessButton.font")); // NOI18N
guessButton.setForeground(resourceMap.getColor("guessButton.foreground")); // NOI18N
guessButton.setText(resourceMap.getString("guessButton.text")); // NOI18N
guessButton.setName("guessButton"); // NOI18N
guessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guessButtonActionPerformed(evt);
}
});
picLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
picLabel.setIcon(resourceMap.getIcon("picLabel.icon")); // NOI18N
picLabel.setText(resourceMap.getString("picLabel.text")); // NOI18N
picLabel.setName("picLabel"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
gameOutput.setBackground(resourceMap.getColor("gameOutput.background")); // NOI18N
gameOutput.setColumns(20);
gameOutput.setRows(5);
gameOutput.setName("gameOutput"); // NOI18N
jScrollPane1.setViewportView(gameOutput);
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jScrollPane1, 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(picLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(guessLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(guessInput, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46)
.addComponent(guessButton)))
.addContainerGap(55, Short.MAX_VALUE))
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(181, 181, 181)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(189, Short.MAX_VALUE))
.addComponent(guesswordOutput, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(guesswordOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(guessLabel)
.addComponent(guessButton)
.addComponent(guessInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(picLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))
.addGap(39, 39, 39))
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(hangmangame.HangmanGameApp.class).getContext().getActionMap(HangmanGameView.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 315, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Initializes the game and displays the empty word for the player
}
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JTextArea gameOutput;
private javax.swing.JButton guessButton;
private javax.swing.JTextField guessInput;
private javax.swing.JLabel guessLabel;
private javax.swing.JLabel guesswordOutput;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JLabel picLabel;
private javax.swing.JProgressBar progressBar;
private javax.swing.JButton startButton;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
private javax.swing.JLabel titleLabel;
// End of variables declaration
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
}
Final Edit:
I moved my for loop to inside the start button code - leaving the initial declaration of the hiddenWord string at the beginning - and it's working fine now. Thanks for the help!
Here is my complete code...
When I run this and click button its showing nullpointer exception at resultset
package com.openbravo.pos.followup;
/**
*
* #author manideep
*/
public class FollowUp extends javax.swing.JPanel implements JPanelView, BeanFactoryApp {
private AppView m_App;
protected DataLogicCustomers dlCustomers;
// CustomerInfo customer;
private AppConfig conf;
// private ListProvider lpr
private DefaultTableModel modelx, model;
protected DataLogicFollowUp dlFollowUp;
/**
* Creates new form FollowUp
*/
public FollowUp() {
initComponents();
String[] args = {};
conf = new AppConfig(args);
conf.load();
jLabel3.setText("");
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
m_jTicketId3 = new javax.swing.JLabel();
m_jTicketId1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jcmdOK = new javax.swing.JButton();
jcmdCancel = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jLabel1.setText("Enter Date");
jTextField1.setPreferredSize(new java.awt.Dimension(90, 19));
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("jLabel3");
jButton3.setText("Customer");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Product");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
m_jTicketId3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
m_jTicketId3.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")), javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
m_jTicketId3.setOpaque(true);
m_jTicketId3.setPreferredSize(new java.awt.Dimension(160, 25));
m_jTicketId3.setRequestFocusEnabled(false);
m_jTicketId1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
m_jTicketId1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")), javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
m_jTicketId1.setOpaque(true);
m_jTicketId1.setPreferredSize(new java.awt.Dimension(160, 25));
m_jTicketId1.setRequestFocusEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE))
.addGap(154, 154, 154)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(m_jTicketId1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jTicketId3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3)
.addComponent(m_jTicketId3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(m_jTicketId1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addGap(24, 24, 24))
);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Customer", "Phone No.", "Product", "Last sold Qty.", "Consumption", "last sale date", "Delivery Date", "Remark 1", "Remark 2", "Stock(Y/N)", "Invoice No."
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, true, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTable1);
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(4).setResizable(false);
jTable1.getColumnModel().getColumn(5).setResizable(false);
jTable1.getColumnModel().getColumn(6).setResizable(false);
jTable1.getColumnModel().getColumn(7).setResizable(false);
jTable1.getColumnModel().getColumn(7).setPreferredWidth(0);
jTable1.getColumnModel().getColumn(8).setResizable(false);
jTable1.getColumnModel().getColumn(9).setResizable(false);
jTable1.getColumnModel().getColumn(10).setResizable(false);
jcmdOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
jcmdOK.setText("OK");
jcmdOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcmdOKActionPerformed(evt);
}
});
jcmdCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
jcmdCancel.setText("Cancel");
jcmdCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcmdCancelActionPerformed(evt);
}
});
jCheckBox1.setText("Select All");
jCheckBox1.setMaximumSize(new java.awt.Dimension(0, 0));
jCheckBox1.setPreferredSize(new java.awt.Dimension(0, 0));
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(353, 353, 353)
.addComponent(jcmdOK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcmdCancel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1408, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(74, 74, 74))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcmdOK)
.addComponent(jcmdCancel))
.addGap(31, 31, 31))
);
}// </editor-fold>//GEN-END:initComponents
private void getListSRLine(Element e){
String customer= getAttrDataFromElement((Element)e.getElementsByTagName("customer").item(0),"identifier");
String phone= getCharacterDataFromElement((Element)e.getElementsByTagName("phone").item(0));
String product=getAttrDataFromElement((Element)e.getElementsByTagName("product").item(0),"identifier");
String lastsoldqty=getCharacterDataFromElement((Element)e.getElementsByTagName("lastsoldqty").item(0));
String consumption=getCharacterDataFromElement((Element)e.getElementsByTagName("consumption").item(0));
String lastsaledate=getCharacterDataFromElement((Element)e.getElementsByTagName("lastsaledate").item(0));
String deliverydate=getCharacterDataFromElement((Element)e.getElementsByTagName("deliverydate").item(0));
String remark1=getCharacterDataFromElement((Element)e.getElementsByTagName("remark1").item(0));
String remark2=getCharacterDataFromElement((Element)e.getElementsByTagName("remark2").item(0));
String stock=getCharacterDataFromElement((Element)e.getElementsByTagName("stock").item(0));
String invoiceno=getCharacterDataFromElement((Element)e.getElementsByTagName("invoiceno").item(0));
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{customer,phone,product,lastsoldqty,consumption,lastsaledate,deliverydate,remark1,remark2,stock,invoiceno});
//sortColumn(model, 1, true);
model.fireTableDataChanged();
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable1.setAutoCreateRowSorter(true);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(150);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(120);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(200);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(50);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(5).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(6).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(7).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(8).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(9).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(10).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(11).setPreferredWidth(0);
}
private void executeSearch() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/openbravopos", "postgres",
"postgres");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
try {
System.out.println("You made it, take control your database now!");
int colCount;
String [] headers;
Statement stmt = null;
// rs=(ResultSet) dlFollowUp.getFollowUpList();
// getFollowUplist();
ResultSet rs = null;
rs = stmt.executeQuery("SELECT id,customer,phone,product,lastsoldqty,consumption,lastsaledate,deliverydate,remark1,remark2,stock,invoiceno FROM followup");
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while(rs.next()){
Object[] objects = new Object[colNo];
for(int i=0;i<colNo;i++){
objects[i]=rs.getObject(i+1);
}
model.addRow(objects);
}
jTable1.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("Failed to make connection!");
}
}
public static String getAttrDataFromElement(Element e,String attr){
return e.getAttribute(attr);
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmdOKActionPerformed
// jButton1ActionPerformed(evt);
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
//dispose();
}//GEN-LAST:event_jcmdOKActionPerformed
private void jcmdCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmdCancelActionPerformed
dispose();
}//GEN-LAST:event_jcmdCancelActionPerformed
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jCheckBox1ActionPerformed
String field="";
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jLabel3.setText("");
executeSearch();
// entity = response.getafilter();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
JCustomerFinder finder = JCustomerFinder.getCustomerFinder(this, dlCustomers);
finder.setVisible(true);
CustomerInfo custsel=finder.getSelectedCustomer();
m_jTicketId3.setText(custsel.printName());
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
/* // TODO add your handling code here:
JProductFinder finder = JProductFinder.getProductFinder(this, dlSales, m_App.getInventoryLocation(),m_App);
finder.setVisible(true);
ProductAttrInfoExt prod = finder.getSelectedProduct();
m_jTicketId1.setText(prod.getName());*/
}//GEN-LAST:event_jButton4ActionPerformed
private void dispose(){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
jLabel3.setText(null);
model.fireTableDataChanged();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton jcmdCancel;
private javax.swing.JButton jcmdOK;
private javax.swing.JLabel m_jTicketId1;
private javax.swing.JLabel m_jTicketId3;
// End of variables declaration//GEN-END:variables
#Override
public String getTitle() {
return "Follow Up";
}
#Override
public void activate() throws BasicException {
resetFollowUp();
}
public void resetFollowUp(){
jTextField1.setText("");
m_jTicketId3.setText("");
m_jTicketId1.setText("");
}
#Override
public boolean deactivate() {
return true;
}
#Override
public JComponent getComponent() {
return this;
}
#Override
public void init(AppView app) throws BeanFactoryException {
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(150);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(150);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(250);
jTable1.getColumnModel().getColumn(3).setPreferredWidth(100);
jTable1.getColumnModel().getColumn(4).setPreferredWidth(200);
jTable1.getColumnModel().getColumn(5).setPreferredWidth(250);
jTable1.getColumnModel().getColumn(6).setPreferredWidth(250);
jTable1.getColumnModel().getColumn(7).setPreferredWidth(250);
jTable1.getColumnModel().getColumn(8).setPreferredWidth(200);
jTable1.getColumnModel().getColumn(9).setPreferredWidth(200);
jTable1.getColumnModel().getColumn(10).setPreferredWidth(100);
DefaultTableModel modelx = (DefaultTableModel) jTable1.getModel();
for(int j=0;j< modelx.getRowCount();j++){
}
m_App=app;
// setWarehouse(m_App.getWarehouseSearchKey());
dlCustomers = (DataLogicCustomers) m_App.getBean("com.openbravo.pos.customers.DataLogicCustomers");
}
#Override
public Object getBean() {
return this;
}
}
You never initialise the Statement object....
Statement stmt = null; // Look ma, I'm null
// rs=(ResultSet) dlFollowUp.getFollowUpList();
// getFollowUplist();
ResultSet rs = null;
// Look ma, I'm still null
rs = stmt.executeQuery("SELECT id,customer,phone,product,lastsoldqty,consumption,lastsaledate,deliverydate,remark1,remark2,stock,invoiceno FROM followup");
You need to create the stmt before you can use...
stmt = connection.createStatement();
You may find reading through the JDBC tutorials of benifit
Problem #2
You define model as instance variable at the start of your FollowUp class...
private DefaultTableModel modelx, model;
But you never initialise it to anything....
I would imagine, based on your code, you would need to initialise it in your executeSearch method...
// You will need to fill this out with appropriate values,
// the number of columns in you JTable should match the
// the number columns from your query...
Object[] columns = new Object[]{....};
model = new DefaultTableModel(columns, 0);
while(rs.next()){
Object[] objects = new Object[colNo];
for(int i=0;i<colNo;i++){
objects[i]=rs.getObject(i+1);
}
model.addRow(objects);
}