Strange NullPointerException in Java Client-Server program - java

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.

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()

Solve the problem of not being able to transfer files

I have studied creating a chat program from a tutorial site and I applied all of the above in the explanation but I have a problem is the inability to transfer files and images between the server and the client.
This code is used in chat.
I've done a lot of experiments, but I can't solve the problem.
MessageList:
public class MessageList extends Thread{
ServerSocket srever;
int port=1000;
WritableGUI gui;
private ObjectOutputStream out;
public MessageList(WritableGUI gui,int port){
this.port=port;
this.gui=gui;
try {
srever=new ServerSocket(port);
} catch (IOException e) {
Logger.getLogger(MessageList.class.getName()).log(Level.SEVERE, null, e);
}
}
#Override
public void run(){
Socket clientSocket;
try {
while ((clientSocket=srever.accept())!=null) {
InputStream is = clientSocket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
if(line !=null){
gui.write(line);
}
}
} catch (Exception e) {
Logger.getLogger(MessageList.class.getName()).log(Level.SEVERE, null, e);
}
}
}
Message:
public class MessageTransmitter extends Thread{
String message , hostname;
int port=1000;
int filesize=2022386;
int bytesRead;
int currentTot = 0;
public MessageTransmitter(){
}
public MessageTransmitter(String message ,String hostname,int port ){
this.message=message;
this.hostname=hostname;
this.port=port;
}
#Override
public void run(){
try {
Socket s =new Socket(hostname,port);
s.getOutputStream().write(message.getBytes());
s.close();
} catch (IOException e) {
Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, e);
}
}
}
WritableGUI :
public interface WritableGUI {
void write(String s);
}
Please help me solve this problem.
public class MainScreen extends javax.swing.JFrame implements WritableGUI {
public MainScreen() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
ip = new javax.swing.JTextField();
Sender = new javax.swing.JTextField();
listen = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
chat = new javax.swing.JTextArea();
mass = new javax.swing.JTextField();
sendB = new javax.swing.JButton();
receiver = new javax.swing.JTextField();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(208, 204, 202));
ip.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
ip.setText("localhost");
ip.setToolTipText("");
ip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ipActionPerformed(evt);
}
});
Sender.setText("200");
listen.setBackground(new java.awt.Color(255, 192, 27));
listen.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
listen.setText("Listen");
listen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
listenActionPerformed(evt);
}
});
chat.setColumns(20);
chat.setRows(5);
jScrollPane1.setViewportView(chat);
sendB.setBackground(new java.awt.Color(255, 192, 27));
sendB.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
sendB.setText("send");
sendB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendBActionPerformed(evt);
}
});
receiver.setText("100");
Exit.setBackground(new java.awt.Color(255, 192, 27));
Exit.setFont(new java.awt.Font("Copperplate Gothic Bold", 0, 13)); // NOI18N
Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(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, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
.addComponent(mass, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Sender)
.addComponent(receiver)
.addComponent(ip, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
.addComponent(listen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Exit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(sendB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(219, 219, 219)
.addComponent(sendB, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Sender, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(receiver, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ip, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(listen, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mass, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(25, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
MessageList listener;
private void listenActionPerformed(java.awt.event.ActionEvent evt) {
listener =new MessageList(this, Integer.parseInt(Sender.getText()));
listener.start();
}
private void sendBActionPerformed(java.awt.event.ActionEvent evt) {
MessageTransmitter mt = new MessageTransmitter(mass.getText(), ip.getText(), Integer.parseInt(receiver.getText()));
mt.start();
}
private void ipActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
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(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.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 MainScreen().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton Exit;
private javax.swing.JTextField Sender;
private javax.swing.JTextArea chat;
private javax.swing.JTextField ip;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton listen;
private javax.swing.JTextField mass;
private javax.swing.JTextField receiver;
private javax.swing.JButton sendB;
// End of variables declaration
#Override
public void write(String ss) {
chat.append(ss+System.lineSeparator());
}
}

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.

Send a command to external process using ProcessBuilder

I'm trying to start a command shell and send the 'dir' command to it. But it isn't working. The code I'm using is based off of the SO question here: Run external program concurrently and communicate with it through stdin / stdout
public static void main(String[] args) throws IOException, InterruptedException {
String params[] = {"cmd.exe"};
ProcessBuilder pb = new ProcessBuilder(params);
Process proc = pb.start();
final Scanner in = new Scanner(proc.getInputStream());
Thread t = new Thread() {
public void run() {
while (in.hasNextLine())
System.out.println(in.nextLine());
}
};
t.start();
PrintWriter out = new PrintWriter(proc.getOutputStream());
Thread.sleep(5000);
out.write("dir");
out.flush();
}
The process is being triggered since I see the following output. But if I try passing any command, it doesn't respond with an output or anything:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
you are executing the command cmd.exe within the command prompt which return the result
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
how about doing this
Process p=Runtime.getRuntime().exec("cmd /c dir");
if you want your program to run behind and receive values
private ExecutorService execService = Executors.newFixedThreadPool(1);
try {
execService.submit(new Runnable() {
#Override
public void run() {
try {
//define the task over here ...
//eg. String command= "your command";
// Process pr = rt.exec(command);
} catch (IOException ex) {}
}
});
} catch (IOException ex) {}
Take look at this program.
There is a main program which has a GUI for adding two numbers.
Behind the screen on the terminal there's another program running which does the same addition operation. Both runs on the same time.
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Myapp extends javax.swing.JFrame {
public Myapp() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
first = new javax.swing.JTextField();
jLabel189 = new javax.swing.JLabel();
jLabel183 = new javax.swing.JLabel();
second = new javax.swing.JTextField();
jLabel184 = new javax.swing.JLabel();
sum = new javax.swing.JTextField();
signbut = new javax.swing.JButton();
signbut1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
first.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jLabel189.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel189.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel189.setText("First Number");
jLabel183.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel183.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel183.setText("Second Number");
second.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jLabel184.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel184.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel184.setText("Sum");
sum.setBackground(new java.awt.Color(255, 255, 255));
sum.setEditable(false);
sum.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
sum.setDisabledTextColor(new java.awt.Color(255, 255, 255));
signbut.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
signbut.setText("CLEAR");
signbut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
signbutActionPerformed(evt);
}
});
signbut1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
signbut1.setText("ADD");
signbut1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
signbut1ActionPerformed(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(10, 10, 10)
.addComponent(jLabel189, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel183, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(second, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel184, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addComponent(signbut, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(signbut1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(26, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel189)
.addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel183)
.addComponent(second, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel184)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(signbut)
.addComponent(signbut1))
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void signbutActionPerformed(java.awt.event.ActionEvent evt) {
sum.setText("");
first.setText("");
second.setText("");
}
private void signbut1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
int a=Integer.parseInt(first.getText());
int b=Integer.parseInt(second.getText());
int c=a+b;
sum.setText(""+c);
}catch(Exception e){
sum.setText("");
first.setText("");
second.setText("");}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
BackProgram b=new BackProgram();
b.getBackendWorker();
new Myapp().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField first;
private javax.swing.JLabel jLabel183;
private javax.swing.JLabel jLabel184;
private javax.swing.JLabel jLabel189;
private javax.swing.JTextField second;
private javax.swing.JButton signbut;
private javax.swing.JButton signbut1;
private javax.swing.JTextField sum;
// End of variables declaration
}
class BackProgram
{
private ExecutorService execService = Executors.newFixedThreadPool(1);
public void getBackendWorker() {
try {
execService.submit(new Runnable() {
#Override
public void run() {
try {
while(true)
{
try{
System.out.println("(BackProgram Class) Enter two Numbers:");
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();
int c=a+b;
System.out.println("Number Sum is:"+c);
}catch(Exception ed){}
}
} catch (Exception ex) {}
}
});
} catch (Exception ex) {}
}
}

Trouble with Reading/Writing to text file program?

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.

Categories

Resources