populating a jcombobox with database information - java

I know I am missing something simple, I think in getting the combobox to access the array.
package my.freelancebillingapp;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import javax.swing.*;
public class billingInfoUI extends javax.swing.JFrame {
public billingInfoUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
hoursWorked = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
flatRate = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
workType = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Billing Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Bleeding Cowboys", 0, 48))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 457, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
hoursWorked.setHorizontalAlignment(javax.swing.JTextField.CENTER);
hoursWorked.setText("Hours Worked");
hoursWorked.setBorder(null);
jLabel1.setText("Or");
flatRate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
flatRate.setText("Flat Rate");
flatRate.setBorder(null);
workType.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Work Type", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
workType.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Web Design", "Graphic Design", "Consulting" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
workType.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(workType);
jList2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Any Extras?", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
jList2.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Blog", "Forum", "Templating", "Rush Delivery" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(jList2);
jButton1.setText("Save");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton2.setText("Invoice");
jButton3.setText("Close");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton3MouseClicked(evt);
}
});
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jComboBox1.setModel(customers);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(89, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(jLabel1)
.addGap(1, 1, 1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(79, 79, 79))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(79, 79, 79)
.addComponent(jButton3)
.addGap(52, 52, 52))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(134, Short.MAX_VALUE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(107, 107, 107))
);
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)
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton1))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
new FreelanceBillingUI().setVisible(true);
setVisible(false);
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String hoursWorkedtxt = hoursWorked.getText();
String flatRatetxt = flatRate.getText();
workType.getSelectedValue();
workType.toString();
Object workTypetxt = workType.getSelectedValue();
if(hoursWorkedtxt.contains("H")){
hoursWorkedtxt = "0";
}else{
flatRatetxt = "0";
}
}
public class CustomerData {
private static final String JDBC_CONNECTION_URL = "jdbc:mysql://localhost/test";
private static final String DATABASE_USER = "root";
private static final String DATABASE_PASSWORD = "root";
private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";
private Connection connection = null;
public CustomerData(){
initConnection();
}
private void initConnection() {
try {
//load the mysql driver
Class.forName("com.mysql.jdbc.Driver");
//create the database connection
connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeConnection(){
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection = null;
}
}
}
public ArrayList fetchCustomerData(){
if (connection != null){
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
return convertResultSetToCustomersArray(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
}
return new ArrayList();
}
private ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
ArrayList customers = new ArrayList();
while (results.next()){
customers.add(results.getString("custName"));
}
return customers;
}
}
private void initData(){
CustomerData customerData = new CustomerData();
ArrayList custArrayList = customerData.fetchCustomerData();
customers = (String[]) custArrayList.toArray(new String[0]);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new billingInfoUI().setVisible(true);
}
});
}
private String[] customers = null;
private javax.swing.JTextField flatRate;
private javax.swing.JTextField hoursWorked;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JList jList2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JList workType;
}

There is too much code there to look at 90% of it is NOT related to adding data in a combo box. You have a dozen other components which clutter the code so we can't see what actually happening with the comobo box.
It you really need help then post a SSCCE.
That is, create a simple frame and load hard coded data into the combo box.
Then create a simple program to read data from the database and use System.out.println(...) to display each value.
Once you've mastered the two basic steps, then put the two programs together to load a combobox dynamically from a database.
Finally add the rest of you components to the frame.
Break you problem down into small, manageable steps and you will be able to debug it easier.

A few points:
Wading through your code, I don't see a call to initData being made anywhere. Without that call, you wont call your database code. Without the database call, you wont get the data.
JComboBox does not have a setModel method that takes an array. You can wrap your array in a DefaultComboBoxModel and set that on the model.
It is good to keep in mind that blocking calls like database access should not be made in the AWT painting thread, and neither should calls that update the GUI be made outside of the AWT thread. You should look into creating your GUI and grabbing your data in separate threads, and making use of SwingUtlities.invokeLater or similar tools to update your GUI.

Related

Java Swing jLabel java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have a class Hangman and one class GUI. Hangman class for the process. So, I want to passing the value String form Hangman class to jLabel in GUI. When I run the project and I am strungling in java.lang.NullPointerException even I wrote the right code. When user click start. The value from class Hangman will show to the jLabel
Hangman class
package hangman;
import java.util.*;
import java.io.*;
import java.awt.*;
public class Hangman {
String filename = "words.txt";
String[] wordList;
String[] wordBanks = {"DISAVOW","KEYHOLE","QUIZZES",
"WHOMEVER","ZIGZIG","WHEEZY","UNWORTHY",
"WHIZZING","JOCKEY","MICROWAVE"};
String[] answer;
int index;
String[] resultarray;
StringBuilder stringbuilder = new StringBuilder();
String resultstring;
public Hangman()
{
initialComponent();
}
public void initialComponent()
{
index = randomIndex();
answer = wordBanks[index].split("");
resultarray = new String[answer.length];
for(int i = 0; i < answer.length ;i++)
{
resultarray[i] = " _ ";
stringbuilder.append(resultarray[i]);
}
resultstring = stringbuilder.toString();
}
public int randomIndex()
{
int rand = 0;
// define the range
int max = 10;
int min = 0;
int range = max - min;
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
rand = (int)(Math.random() * range) + min;
// Output is different everytime this code is executed
//System.out.println(rand);
}
return rand;
}
public void printWord()
{
System.out.println(wordBanks[randomIndex()].toString() + "|" + wordBanks[randomIndex()].length());
}
public void initialWord()
{
int random = randomIndex();
//answer = new String[random];
answer = wordBanks[random].split("");
for (int i = 0; i < answer.length;i++)
System.out.println(answer[i]);
}
public static void main(String[] args) {
// TODO code application logic here
Hangman hangman = new Hangman();
GUI gui = new GUI();
gui.setVisible(true);
}
}
GUI class
'''
package hangman;
public class GUI extends javax.swing.JFrame {
Hangman hangman;
/**
* Creates new form GUI
*/
public GUI() {
initComponents();
//defaultResult();
}
public void defaultResult()
{
jLabelGuess.setText(hangman.resultstring);
}
#SuppressWarnings("unchecked")
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jButtonStart = new javax.swing.JButton();
jButtonA = new javax.swing.JButton();
jButtonB = new javax.swing.JButton();
jButtonC = new javax.swing.JButton();
jButtonD = new javax.swing.JButton();
jButtonE = new javax.swing.JButton();
jButtonF = new javax.swing.JButton();
jButtonG = new javax.swing.JButton();
jButtonH = new javax.swing.JButton();
jButtonI = new javax.swing.JButton();
jButtonJ = new javax.swing.JButton();
jButtonO = new javax.swing.JButton();
jButtonP = new javax.swing.JButton();
jButtonQ = new javax.swing.JButton();
jButtonR = new javax.swing.JButton();
jButtonK = new javax.swing.JButton();
jButtonS = new javax.swing.JButton();
jButtonL = new javax.swing.JButton();
jButtonT = new javax.swing.JButton();
jButtonN = new javax.swing.JButton();
jButtonM = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jButtonO1 = new javax.swing.JButton();
jButtonP1 = new javax.swing.JButton();
jButtonK1 = new javax.swing.JButton();
jButtonL1 = new javax.swing.JButton();
jButtonN1 = new javax.swing.JButton();
jButtonM1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabelAtemp = new javax.swing.JLabel();
jLabelGuess = new javax.swing.JLabel();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Welcome to Hangman");
jButtonStart.setText("Start");
jButtonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStartActionPerformed(evt);
}
});
jButtonA.setText("A");
jButtonB.setText("B");
jButtonC.setLabel("C");
jButtonD.setText("D");
jButtonD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDActionPerformed(evt);
}
});
jButtonE.setText("E");
jButtonF.setText("F");
jButtonG.setText("G");
jButtonH.setText("H");
jButtonH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonHActionPerformed(evt);
}
});
jButtonI.setText("I");
jButtonJ.setText("J");
jButtonJ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonJActionPerformed(evt);
}
});
jButtonO.setText("O");
jButtonO.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOActionPerformed(evt);
}
});
jButtonP.setText("P");
jButtonQ.setText("Q");
jButtonR.setText("R");
jButtonK.setText("K");
jButtonK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonKActionPerformed(evt);
}
});
jButtonS.setText("S");
jButtonS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSActionPerformed(evt);
}
});
jButtonL.setText("L");
jButtonT.setText("T");
jButtonN.setText("N");
jButtonN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonNActionPerformed(evt);
}
});
jButtonM.setText("M");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 256, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jButtonO1.setText("O");
jButtonO1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonO1ActionPerformed(evt);
}
});
jButtonP1.setText("P");
jButtonK1.setText("K");
jButtonK1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonK1ActionPerformed(evt);
}
});
jButtonL1.setText("L");
jButtonN1.setText("N");
jButtonN1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonN1ActionPerformed(evt);
}
});
jButtonM1.setText("M");
jLabel2.setText("Atemps left:");
jLabelAtemp.setText("jLabel3");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButtonN1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonO1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonP1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(189, 189, 189))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jButtonK1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonL1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonM1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonA, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonB, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonC, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonD, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonK, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonL, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonM, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonN, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonO, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonP, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonQ, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonR, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonS, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonT, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(163, 163, 163)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonE, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonF, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonG, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonH, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonI, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonJ, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(192, 192, 192)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jButtonStart))
.addGap(18, 18, 18)
.addComponent(jLabelAtemp)))
.addGap(155, 155, 155)))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
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(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(35, 35, 35)
.addComponent(jLabelGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonA)
.addComponent(jButtonB)
.addComponent(jButtonC)
.addComponent(jButtonD)
.addComponent(jButtonE)
.addComponent(jButtonF)
.addComponent(jButtonG)
.addComponent(jButtonH)
.addComponent(jButtonI)
.addComponent(jButtonJ))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonK)
.addComponent(jButtonL)
.addComponent(jButtonM)
.addComponent(jButtonO)
.addComponent(jButtonP)
.addComponent(jButtonQ)
.addComponent(jButtonR)
.addComponent(jButtonS)
.addComponent(jButtonT)
.addComponent(jButtonN))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonK1)
.addComponent(jButtonL1)
.addComponent(jButtonM1)
.addComponent(jButtonO1)
.addComponent(jButtonP1)
.addComponent(jButtonN1))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabelAtemp))
.addGap(29, 29, 29)
.addComponent(jButtonStart)))
.addGap(19, 19, 19))
);
pack();
}// </editor-fold>
private void jButtonDActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonHActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonJActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonOActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonSActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButtonNActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButtonKActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonO1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButtonK1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonN1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabelGuess.setText(hangman.resultstring);
}
/**
* #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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//Hangman hangman = new Hangman();
//GUI gui = new GUI();
//gui.setVisible(true);
/* Create and display the form */
/*java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new GUI().setVisible(true);
}
});*/
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonA;
private javax.swing.JButton jButtonB;
private javax.swing.JButton jButtonC;
private javax.swing.JButton jButtonD;
private javax.swing.JButton jButtonE;
private javax.swing.JButton jButtonF;
private javax.swing.JButton jButtonG;
private javax.swing.JButton jButtonH;
private javax.swing.JButton jButtonI;
private javax.swing.JButton jButtonJ;
private javax.swing.JButton jButtonK;
private javax.swing.JButton jButtonK1;
private javax.swing.JButton jButtonL;
private javax.swing.JButton jButtonL1;
private javax.swing.JButton jButtonM;
private javax.swing.JButton jButtonM1;
private javax.swing.JButton jButtonN;
private javax.swing.JButton jButtonN1;
private javax.swing.JButton jButtonO;
private javax.swing.JButton jButtonO1;
private javax.swing.JButton jButtonP;
private javax.swing.JButton jButtonP1;
private javax.swing.JButton jButtonQ;
private javax.swing.JButton jButtonR;
private javax.swing.JButton jButtonS;
private javax.swing.JButton jButtonStart;
private javax.swing.JButton jButtonT;
private javax.swing.JFrame jFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelAtemp;
private javax.swing.JLabel jLabelGuess;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
The message error when I run the application.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at hangman.GUI.jButtonStartActionPerformed(GUI.java:400)
at hangman.GUI.access$000(GUI.java:12)
at hangman.GUI$1.actionPerformed(GUI.java:96)
It seems that in the GUI class you declare a member variable, Hangman hangman, but you never initialize it. Therefore, the code jLabelGuess.setText(hangman.resultstring); and similar calls will result in a null pointer exception.
In the GUI class, you just only declare Hangman hangman, which mean the class Hangman has never been called to execute or initialized any value. Therefore, hangman.resultstring is null when you called jLabelGuess.setText(hangman.resultstring), since resultstring value is get from Hangman class; and cause Null Pointer Exception error at jLabelGuess.setText() and the function jButtonStartActionPerformed()
You might fix it if you initialize the Hangman class: Hangman hangman = new Hangman(); Or calling the function that initializes the value of resultstring which is hangman.initialComponent()

Access txtField value from another class

I want to get the value from my Jframe textfield to another class.
Why does it not work in my example?
I've created a getter in the main JFrame class that returns me txtIP1, this is a Textfield inside my frame.
In the method bepaalklasse inside the secondary class i'm trying to get the content of my textfield txtIP1 and parse it to an integer so i can use it for the method.
Secondary Class
private int iKlasse_;
private String sKlasse_;
private JFrame JFrame;
public void setiKlasse_(int iKlasse_) {
this.iKlasse_ = iKlasse_;
}
public void BepaalKlasse() {
iKlasse_ = Integer.parseInt(JFrame.getTxtIP1().getText());
System.out.println("iKlasse_" + iKlasse_);
try {
if (JFrame.getTxtIP1().getText().isEmpty()) {
throw new IOException();
}
if ((iKlasse_ >= 0) && ((iKlasse_) <= 127)) {
sKlasse_ = "A Klasse";
} else if ((iKlasse_ > 127) && ((iKlasse_ <= 191))) {
sKlasse_ = "B Klasse";
} else if ((iKlasse_ > 191) && ((iKlasse_ <= 223))) {
sKlasse_ = "C Klasse";
} else if ((iKlasse_ > 223)) {
sKlasse_ = "N/B";
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Gelieve een cijfer in te voeren in het eerste vak", "Leeg IP veld!", JOptionPane.ERROR_MESSAGE);
}
}
public String getsKlasse_() {
return sKlasse_;
}
}
Main Class
private clsInput oInput = new clsInput();
static private clsKlasse oKlasse = new clsKlasse();
private String sKlasse;
protected int iGeselecteerd;
public JFrame() {
initComponents();
iniCombobox();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
txtaDisplay = new javax.swing.JTextArea();
btnKies = new javax.swing.JButton();
btnPrinten = new javax.swing.JButton();
txtIP1 = new javax.swing.JTextField();
txtIP2 = new javax.swing.JTextField();
txtIP3 = new javax.swing.JTextField();
txtIP4 = new javax.swing.JTextField();
cmbSubnetten = new javax.swing.JComboBox<>();
jLabel1 = new javax.swing.JLabel();
lblKlasse = new javax.swing.JLabel();
btnBerekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtaDisplay.setColumns(20);
txtaDisplay.setRows(5);
jScrollPane1.setViewportView(txtaDisplay);
btnKies.setText("Kies");
btnKies.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKiesActionPerformed(evt);
}
});
btnPrinten.setText("Export");
jLabel1.setText("Klasse:");
btnBerekenen.setText("bereken");
btnBerekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBerekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(txtIP1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIP4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(cmbSubnetten, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnKies, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblKlasse, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBerekenen))
.addComponent(btnPrinten))
.addContainerGap(35, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtIP1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIP4, 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(btnBerekenen, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbSubnetten, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnKies, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(lblKlasse, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPrinten)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnKiesActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DoorzendenCmb();
oInput.Subnetten();
}
private void btnBerekenenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
InstellenKlasse();
}
/**
* #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(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnBerekenen;
private javax.swing.JButton btnKies;
private javax.swing.JButton btnPrinten;
private javax.swing.JComboBox<String> cmbSubnetten;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblKlasse;
public javax.swing.JTextField txtIP1;
private javax.swing.JTextField txtIP2;
private javax.swing.JTextField txtIP3;
private javax.swing.JTextField txtIP4;
private javax.swing.JTextArea txtaDisplay;
// End of variables declaration
public JTextField getTxtIP1() {
return txtIP1;
}
public JTextField getTxtIP2() {
return txtIP2;
}
public JTextField getTxtIP3() {
return txtIP3;
}
public JTextField getTxtIP4() {
return txtIP4;
}
private void iniCombobox() { //ini van Combobox (1-10)
for (int i = 0; i < 10; i++) {
cmbSubnetten.addItem(String.valueOf(i));
}
}
private void DoorzendenCmb() {
iGeselecteerd = Integer.parseInt(cmbSubnetten.getSelectedItem().toString());
oInput.setiGeselecteerd(iGeselecteerd);
}
private void InstellenKlasse(){
sKlasse = oKlasse.getsKlasse_();
lblKlasse.setText(sKlasse);
}
}

Junit Testing for GUI

I have following Simple Utility Calculator
Now i want to apply some Junit Testing here.
I don't know how to perform a Junit testing on Gui.
So kindly help me out.
Code is:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculator;
import java.io.*;
import java.text.DecimalFormat;
/**
*
* #author owner
*/
public class Calculator_Utility extends javax.swing.JFrame {
/**
* Creates new form Calculator_Utility
*/
public Calculator_Utility() {
initComponents();UsePowerKw.setText("4.0");
}
/**
* 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.
*/
private void setComponentsName(){
AddButton.setName("Add");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
CostPerKW = new javax.swing.JLabel();
SelectAppliance = new javax.swing.JLabel();
PowerUsage = new javax.swing.JLabel();
NumberHoursUse = new javax.swing.JLabel();
TotalCostApp = new javax.swing.JLabel();
AddButton = new javax.swing.JButton();
CostPerKwTextField = new javax.swing.JTextField();
UsePowerKw = new javax.swing.JTextField();
HourUse = new javax.swing.JTextField();
CostApp = new javax.swing.JTextField();
AllTotal = new javax.swing.JLabel();
AllTotalApp = new javax.swing.JTextField();
SelectApp = new javax.swing.JComboBox<>();
Showfield = new javax.swing.JTextField();
GallonWater = new javax.swing.JLabel();
GallonWat = new javax.swing.JTextField();
Export = new javax.swing.JButton();
CostGallon = new javax.swing.JLabel();
CostGall = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
CostPerKW.setText("Cost Per KW Hour:");
SelectAppliance.setText("Select Appliance:");
PowerUsage.setText("Power Usage In KW Hours:");
NumberHoursUse.setText("Number of Hours use per day:");
TotalCostApp.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
TotalCostApp.setText("Total Cost For Appliance");
AddButton.setText("ADD");
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddButtonActionPerformed(evt);
}
});
CostPerKwTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CostPerKwTextFieldActionPerformed(evt);
}
});
UsePowerKw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsePowerKwActionPerformed(evt);
}
});
AllTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
AllTotal.setText("Total of All Appliances");
SelectApp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Refrigerator", "Washer", "Dryer", "Freezer", "Air Conditioner" }));
SelectApp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SelectAppActionPerformed(evt);
}
});
GallonWater.setText("Gallon of Water:");
Export.setText("Export");
Export.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExportActionPerformed(evt);
}
});
CostGallon.setText("Cost Per Gallon:");
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.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(NumberHoursUse)
.addComponent(SelectAppliance)
.addComponent(PowerUsage)
.addComponent(CostPerKW))
.addComponent(CostGallon, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(GallonWater, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(4, 4, 4))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(AllTotal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(Export)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(TotalCostApp)
.addGap(4, 4, 4)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(AddButton)
.addGap(24, 24, 24))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AllTotalApp, CostApp, CostGall, CostPerKwTextField, GallonWat, HourUse, SelectApp, UsePowerKw});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostPerKW)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SelectAppliance)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PowerUsage)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NumberHoursUse)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(GallonWater)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostGallon)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(TotalCostApp))
.addComponent(AddButton))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotal))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Export))
.addContainerGap())
);
pack();
}// </editor-fold>
//Declare Variables and intialize the variables
private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
double answer;
double total = 0;
String s = SelectApp.getSelectedItem().toString();
//Check if user select "Washer" from drop down box, calculate usage with Gallon
if (s=="Washer") {
//DecimalFormat df= new DecimalFormat("#.##");
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
number4 = (int)((Double.parseDouble(GallonWat.getText())));
answer = number1*number2*number3;
total =+ answer;
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
}
//if user select any appliances other than washer calculate usage
else
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
answer = number1*number2*number3;
total =+ answer;
//Calculated amount is put into field
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
// TODO add your handling code here:
}
//Action listener/Events for JCombo. Pre-defined Power Usage for Each Appliacnes
private void SelectAppActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String s=SelectApp.getSelectedItem().toString();
double r=4;
double w=7;
double x=12;
double y=16;
double z=24;
if (s=="Refrigerator"){
UsePowerKw.setText(String.valueOf(r));
}
else if (s=="Washer") {UsePowerKw.setText(String.valueOf(w));}
else if (s=="Dryer") {UsePowerKw.setText(String.valueOf(x));}
else if (s=="Freezer") {UsePowerKw.setText(String.valueOf(y));}
else UsePowerKw.setText(String.valueOf(z));
}
private void UsePowerKwActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//If jComboBox1 = "Refrigerator" then set jTextField4 = 22
}
//Action Listener/Event creates Data.txt with output
private void ExportActionPerformed(java.awt.event.ActionEvent evt) {
File file = new File("Data.txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = Showfield.getText();
//"The quick brown fox" +
//System.getProperty("line.separator") +
//"jumps over the lazy dog.";
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
}
}
private void CostPerKwTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.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 Calculator_Utility().setVisible(true);
}
});
}
public double number1, number2, number3, number4;
// Variables declaration - do not modify
private javax.swing.JButton AddButton;
private javax.swing.JLabel AllTotal;
private javax.swing.JTextField AllTotalApp;
private javax.swing.JTextField CostApp;
private javax.swing.JTextField CostGall;
private javax.swing.JLabel CostGallon;
private javax.swing.JLabel CostPerKW;
private javax.swing.JTextField CostPerKwTextField;
private javax.swing.JButton Export;
private javax.swing.JTextField GallonWat;
private javax.swing.JLabel GallonWater;
private javax.swing.JTextField HourUse;
private javax.swing.JLabel NumberHoursUse;
private javax.swing.JLabel PowerUsage;
private javax.swing.JComboBox<String> SelectApp;
private javax.swing.JLabel SelectAppliance;
private javax.swing.JTextField Showfield;
private javax.swing.JLabel TotalCostApp;
private javax.swing.JTextField UsePowerKw;
// End of variables declaration
}
Any testCase you can apply like proper working , (actual== expected Result) etc.
You can't test the GUI with JUnit. You can only test the methods.
For example you have a JButton with an actionListener witch calls the method calculate(1, 1):
JButton showDialogButton = new JButton("Text Button");
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
calculate(1, 1);
}
});
private int calculate(int n1, int n2){
return n1 + n2;
}
Now, You cant test the JButton but you can test the method "calculate". We know that calculate(1, 1) will return us 2 so we test it:
assertEquals(2, calculate(1, 1));
This means, that you cannot "press the button with JUnit" but you can test the action the button does.

Cant add dynamically created checkbox to jPanel

I want to add checkboxes to a jpanel, which is on a jFrame. The UI was made on netbeans and i have copied the code to work on its functionality on eclipse.
I cant get my checkboxes come over the Jpanel.
The code
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.border.Border;
public class QueryBuilderUI extends javax.swing.JFrame {
QueryBuilderMethods objQBM = new QueryBuilderMethods();
DefaultComboBoxModel<String> repoModel = new DefaultComboBoxModel<String>();
public QueryBuilderUI() {
getRepositoryListing();
initComponents();
}
private void getRepositoryListing()
{
repoModel = new QueryBuilderMethods().getAllRepositoryName();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Choose Repository");
jComboBox1.setModel(repoModel);
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
jLabel2.setText("Choose Table");
//jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox2ItemStateChanged(evt);
}
});
jLabel3.setText("Choose Columns");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
Border border = BorderFactory.createTitledBorder("Select Columns");
jPanel1.setBorder(border);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 459, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 124, Short.MAX_VALUE)
);
jTextField1.setText("jTextField1");
jLabel4.setText("Generated Query");
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.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(65, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange()== ItemEvent.SELECTED){
Object item = evt.getItem();
DefaultComboBoxModel<String> modelTable = objQBM.getAllTablesForRepo(item.toString());
jComboBox2.setModel(modelTable);
}
}
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange()== ItemEvent.SELECTED){
Object item = evt.getItem();
String RepoName = jComboBox1.getSelectedItem().toString();
List<String> columnNames = objQBM.getAllColumnsForTable(item.toString());
addCheckBox(columnNames);
}
}
private void addCheckBox(List<String> columnNames)
{
int numberCheckBox = columnNames.size();
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for(int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("hi"+i);
jPanel1.add(checkBoxList[i]);
}
jPanel1.revalidate();
}
public static void main(String args[]) {
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
new QueryBuilderUI().setVisible(true);
// }
// });
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
the UI Looks like this
The checkboxes needs to be created dynamically according to what is selected on jComboBox2.
Your jPanel1 JPanel is being constrained by its layout, GroupLayout, which does not take kindly to the addition of new components without significant additions to code that are difficult to make, since GroupLayout was not built to be used for hand coding but rather for GUI-builder coding. I suggest that you build your GUI with much more coder-friendly layouts, or better still, combinations of nested JPanels each using a simpler layout, ones that are much more conducive to the addition of new components, and then your problems will be more easily solved.
You could even still use GroupLayout for the main of your GUI if you desire, but just not for jPanel1. I suggest that you consider using GridLayout or GridBagLayout to add a grid of JCheckBoxes. Or even FlowLayout. For example the following code uses the default JPanel's FlowLayout:
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.border.Border;
public class QueryBuilderUI extends javax.swing.JFrame {
protected static final int PREF_W = 400;
protected static final int PREF_H = 200;
QueryBuilderMethods objQBM = new QueryBuilderMethods();
DefaultComboBoxModel<String> repoModel = new DefaultComboBoxModel<String>();
public QueryBuilderUI() {
getRepositoryListing();
initComponents();
}
private void getRepositoryListing() {
repoModel = new QueryBuilderMethods().getAllRepositoryName();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel() {
#Override
// !! so the JPanel has some size. This is a shameless kludge *****
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Choose Repository");
jComboBox1.setModel(repoModel);
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
jLabel2.setText("Choose Table");
// jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
// "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox2ItemStateChanged(evt);
}
});
jLabel3.setText("Choose Columns");
// *************** Note Changes Below ****************
// !! javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
// !! jPanel1);
// !! jPanel1.setLayout(jPanel1Layout);
// !! jPanel1 now uses JPanel's default FlowLayout
Border border = BorderFactory.createTitledBorder("Select Columns");
jPanel1.setBorder(border);
jTextField1.setText("jTextField1");
jLabel4.setText("Generated Query");
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.LEADING)
.addComponent(
jLabel1)
.addComponent(
jLabel2))
.addGap(57, 57, 57)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jComboBox1,
javax.swing.GroupLayout.PREFERRED_SIZE,
106,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jComboBox2,
javax.swing.GroupLayout.PREFERRED_SIZE,
106,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(
jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
412,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(65, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object item = evt.getItem();
DefaultComboBoxModel<String> modelTable = objQBM
.getAllTablesForRepo(item.toString());
jComboBox2.setModel(modelTable);
}
}
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object item = evt.getItem();
String RepoName = jComboBox1.getSelectedItem().toString();
List<String> columnNames = objQBM.getAllColumnsForTable(item
.toString());
addCheckBox(columnNames);
}
}
private void addCheckBox(List<String> columnNames) {
int numberCheckBox = columnNames.size();
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
System.out.println("numberCheckBox = " + numberCheckBox);
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("hi" + i);
jPanel1.add(checkBoxList[i]);
}
jPanel1.revalidate();
jPanel1.repaint();
System.out.println("check boxes added");
}
public static void main(String args[]) {
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
new QueryBuilderUI().setVisible(true);
// }
// });
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
// mock code added so that the above code will compile and run
// because you didn't give us this code
class QueryBuilderMethods {
public DefaultComboBoxModel<String> getAllRepositoryName() {
DefaultComboBoxModel<String> cModel = new DefaultComboBoxModel<>();
for (String item : new String[] { "one", "two", "three", "four", "five" }) {
cModel.addElement(item);
}
return cModel;
}
public List<String> getAllColumnsForTable(String string) {
List<String> columns = new ArrayList<>();
for (String item : new String[] { "col 1", "col 2", "col 3", "col 4" }) {
columns.add(item);
}
return columns;
}
public DefaultComboBoxModel<String> getAllTablesForRepo(String string) {
DefaultComboBoxModel<String> cModel = new DefaultComboBoxModel<>();
for (String item : new String[] { "repo one", "repo two", "repo three",
"repo four", "repo five" }) {
cModel.addElement(item);
}
return cModel;
}
}

Display resultset in custom jtable

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

Categories

Resources