Send a command to external process using ProcessBuilder - java

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

Related

GUI Program freezes once inside action performed method in java [duplicate]

This question already has answers here:
GUI Freezes During While Loop in Java
(1 answer)
The program freezes when i put a while loop in a action listener
(1 answer)
Closed 2 years ago.
I am attempting to redirect my system.out.println to dislpay to the JTextArea element of the GUI (hence it being public and static so that the methods that print something can print to it.
But once it gets to the line:
System.out.println("sdsdsdsdsa");
the program just does not go any further. The next two lines are:
System.setOut(printStream);
System.setErr(printStream);
which it does not seem to print out and when I exit the program this error appears:
"Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "main""
and I am unable to verify whether printStream is null or not because the debugger does not seem to following into the action performed method once the start button (JButton1) is pressed.
Below is the main class in the GUI:
public class TrainingProgramme {
static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));
public static void main(String[] args) {
TrainingProgrammeGUI gui = new TrainingProgrammeGUI();
gui.setVisible(true);
System.setOut(printStream);
System.setErr(printStream);
System.out.println("==================================\n"+
"* WELCOME TO CATCH ME IF YOU CAN *\n"+
"==================================\n");
}
GUI class:
package javaapplication2;
import java.awt.event.ActionEvent;
import java.io.PrintStream;
import java.util.Scanner;
/*
* 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.
*/
/**
*
* #author viljo
*/
public class TrainingProgrammeGUI extends javax.swing.JFrame {
static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));
double startTimer = System.nanoTime();
double stopTimer = 0;
Scanner scan = new Scanner(System.in);
Player gameCharacter = null;
Teacher teacher = null;
int finishedProgram = 0;
int userChoice = -1;
/**
* Creates new form TrainingProgrammeGUI
*/
public TrainingProgrammeGUI() {
initComponents();
}
/**
* 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() {
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767));
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel1.setText("CIA Training Programme");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setText("Game: ");
jButton1.setText("Start Game");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton3.setText("What is this game?");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setText("Type Here: ");
jButton4.setText("Exit");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(159, 159, 159))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(261, 261, 261)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(170, 170, 170)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(175, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(20, 20, 20))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
TrainingProgrammeGUI programme = new TrainingProgrammeGUI();
programme.setVisible(true);
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.print("\nThank you for using our training programme!");
System.exit(0);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("sdsdsdsdsa");
System.setOut(printStream);
System.setErr(printStream);
System.out.println("==================================\n"+
"* WELCOME TO CATCH ME IF YOU CAN *\n"+
"==================================\n");
userChoice = TrainingProgramme.checkInputWithPhrase("1.) Start Game\n2.) What is this game?\n3.) Quit", 1, 3);
teacher = new Teacher("John Doe", "Teacher");
gameCharacter = teacher.introductionLines(); // teacher reads a few lines and asks questions then returns Player class
boolean userFinished = false;
gameCharacter.getHotelRoom().setPlayerHere(true);
do { // Checks which room player is in then reads instructions for room. Loop finishes when player wants to chooses suspect
if (gameCharacter.getHotelKitchen().isPlayerHere()) {
if ("HotelRoom".equals((gameCharacter.getHotelKitchen().instructions(teacher)))) {
System.out.println("\nRoom chosen!\n");
gameCharacter.getHotelKitchen().setPlayerHere(false); // Takes player out of current room
gameCharacter.getHotelRoom().setPlayerHere(true); // Puts players into chosen room
}
} else {
if ("Choose".equals((gameCharacter.getHotelRoom().instructions(teacher)))) {
stopTimer = System.nanoTime();
Player.timeTaken = (stopTimer - startTimer) / 10000000; //time taken to finish inspecting items (in seconds)
teacher.chooseWhoDidIt(gameCharacter);
finishedProgram = 1; //Stop the curret loop
userFinished = true; //Stop the main menu loop
} else {
System.out.println("\nKitchen chosen!\n");
gameCharacter.getHotelRoom().setPlayerHere(false);// Takes player out of current room
gameCharacter.getHotelKitchen().setPlayerHere(true);// Puts players into chosen room
}
}
} while (userFinished == false);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("\n+===========================================================+");
System.out.println("|This game was created to help train our new junior recruits|");
System.out.println("+===========================================================+\n\n");
System.out.println("Objective: Gather evidence by looking for clues\n"+
"and once you are done go back to the room to guess \n"+
"which suspect did it. Suspects are provided once you have\n"+
"went back to the room and decided to guess who did the crime!\n");
}
// Variables declaration - do not modify
private javax.swing.Box.Filler filler1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
PrintStream class:
package net.codejava.swing;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* This class extends from OutputStream to redirect output to a JTextArrea
* #author www.codejava.net
*
*/
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}

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.

Strange NullPointerException in Java Client-Server program

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.

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