Date and time not updating - java

My program uses dates to check when an engineer has visited a machine. The only problem with this is that the date does not remain up to date. The date and time that the machine displays is the exact time that the machine was started. Not when the button was clicked. Any assistance would be helpful.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}

You never re-initialize date, you're just updating storedDate with the existing date in login. You could change this line in login
storedDate = date;
to
storedDate = new Date();
And then (I think) you can remove date.

Date does not keep a persistent current time. Date is backed by a long that is set when the Date is instantiated and is never changed.
You can either make a new Date() in your logon method, so it would be created when the user logs on, or just use System.currentTimeMillis() to get the current time as a long.

Related

How to display each instance of a user logging into a server with a button click?

I have been tasked with creating a recycling machine server which a engineer can log into empty, reset, etc. Each time the engineer logs into a machine it creates a string that says "Engineer has logged in on this (date)". I need to create a JButton that prints out each instance of this string being written.
So when pressed it prints out something like this:
"Engineer visited this machine on 01/01/2016"
"Engineer visited this machine on 02/01/2016"
"Engineer visited this machine on 05/04/2016"
The log in function is working and uses stored cookies to figure out if the user has input the correct information. I am however unable to figure out how to print out this summary of visits via one button click. Any help would be appreciated.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits = 0;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = new Date();
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
So after working around with the code for a while I discovered that there was one simple piece of code that was causing it to not display the information I wanted.
private int numberOfVisits = 0;
Defining the int as a 0 to begin with caused the code to reset the value of the int every time I pressed the "visits" button.
Removing the 0 fixed this issue.
private int numberOfVisits;

Break a while(true) dependency from class A that depends on class B

Consider the following class that just gets an IP and port number :
package view;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
* Server side
* #author X
*
*/
class ServerConnector implements ActionListener
{
private JFrame m_frame = null;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
private String m_ip;
private String m_port;
private boolean ready = false;
/**
* Ctor
*/
ServerConnector()
{
m_frame = new JFrame("Sever Side Listener");
m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
gui.setSize(m_sizeX , m_sizeY);
m_frame.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
m_frame.setLocation(m_centerX , m_centerY);
m_frame.setSize(m_sizeX , m_sizeY);
m_frame.pack();
m_frame.setVisible(true);
}
public static void main(String[] args) {
new ServerConnector();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton)
{
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try
{
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try
{
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
m_frame.dispose();
this.m_ip = ip;
this.m_port = port;
ready = true;
// new ServerGUI(ip , s_port);
}
}
public boolean isReady()
{
return this.ready;
}
/**
*
* #return
*/
public String[] getIPandPort()
{
String[] ipPort = new String[2];
ipPort[0] = this.m_ip;
ipPort[1] = this.m_port;
return ipPort;
}
}
And the would be controller class
public class ServerController {
String m_ip;
int m_port;
public static void main(String args[])
{
ServerConnector sc = new ServerConnector();
while (!sc.isReady())
{
// run
}
// get IP and port
String[] ipPort = sc.getIPandPort();
System.out.println("IP is :" + ipPort[0] + " and port is :" + ipPort[1]);
}
}
For now ServerController is in a while(true) loop , until the user has entered the IP and Port.
How can I avoid this kind of dependency (avoid the while loop) ?
First of all, get rid of the while (true) loop as its only purpose will be to mess your code up.
A general solution is to get the information from the user in code that blocks program flow. A problem occurs, though if this is needed in a GUI that cannot have its event thread blocked.
One Swing solution is as we have discussed previously in your previous question: use a modal dialog to get the information. The modality of the dialog will halt the program flow in the calling code until the dialog is handled.
If you want to avoid use of modal dialogs, then another general event-driven solution is to use a observer design pattern -- have one object be notified by another when information or state has changed. This can be achieved easily with use of PropertyChangeSupport and PropertyChangeListeners, although there are other ways as well, including using the XxxxListeners available in the Swing library.
For example of listener use and MVC with Swing:
Modifying independent JPanels from the JFrame
Java keeps adding buttons! - JFrames
Edit
For example, changes marked with a // !! comment:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.SwingPropertyChangeSupport;
public class ServerController {
String m_ip;
int m_port;
private static String[] ipPort;
public static void main(String args[]) {
final ServerConnector sc = new ServerConnector();
sc.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (ServerConnector.READY.equals(evt.getPropertyName())) {
if (sc.isReady()) {
ipPort = sc.getIPandPort();
System.out.println("IP is :" + ipPort[0] + " and port is :" + ipPort[1]);
}
}
}
});
}
}
class ServerConnector implements ActionListener {
public static final String READY = "ready"; //!!
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(this); //!!
private boolean ready = false;
private JFrame m_frame = null;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
private String m_ip;
private String m_port;
/**
* Ctor
*/
ServerConnector() {
m_frame = new JFrame("Sever Side Listener");
m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
gui.setSize(m_sizeX, m_sizeY);
m_frame.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0, 1));
JPanel controls = new JPanel(new GridLayout(0, 1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
m_frame.setLocation(m_centerX, m_centerY);
m_frame.setSize(m_sizeX, m_sizeY);
m_frame.pack();
m_frame.setVisible(true);
}
public static void main(String[] args) {
new ServerConnector();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton) {
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try {
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try {
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
m_frame.dispose();
this.m_ip = ip;
this.m_port = port;
setReady(true); //!!
// !! ready = true;
// new ServerGUI(ip , s_port);
}
}
// !! added
public void setReady(boolean ready) {
boolean oldValue = this.ready;
boolean newValue = ready;
this.ready = ready;
pcSupport.firePropertyChange(READY, oldValue, newValue);
}
//!! added
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
//!! added
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public boolean isReady() {
return this.ready;
}
/**
*
* #return
*/
public String[] getIPandPort() {
String[] ipPort = new String[2];
ipPort[0] = this.m_ip;
ipPort[1] = this.m_port;
return ipPort;
}
}

Weather API display in JFrame

I am trying to create an java/swing based application which shows weather. So far I have created background and textfield + button to get the location but I do not know how to connect it so it shows and changes the background to another image. I am sorry if that's a noob question, but I never did java before (just processing and arduino plus web design) and my uni forced me to use advanced java with knowledge I never did anything like that before.
Here is my code so far:
package AppPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ApplicationWidget extends JFrame implements ActionListener {
ImageIcon basic;
JLabel label1;
JFrame frame;
JLabel label;
JTextField textfield;
JButton button;
public static void main (String[]args){
ApplicationWidget gui = new ApplicationWidget();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(320, 480);
}
public ApplicationWidget() {
setLayout(new FlowLayout());
WeatherAPI weather = new WeatherAPI("44418");
System.out.println(WeatherAPI.theWeatherRSS);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
label = new JLabel("Welcome! Please Enter your location");
add(label);
textfield = new JTextField(15);
add(textfield);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
button = new JButton("Check weather");
add(button);
basic = new ImageIcon(getClass().getResource("basicback.jpg"));
label1 = new JLabel(basic);
add(label1);
/*add design here*/
/*add mouse interaction*/
/*add image capture*/
}
#Override
public void actionPerformed(ActionEvent e){
JButton button = (JButton) e.getSource();
if (e.getSource() == button){
String data = textfield.getText();
System.out.println(data);
}
}
}
And the WeatherAPI code:
package AppPackage;
import java.net.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.io.*;
public class WeatherAPI
{
static String theWeatherRSS;
static String theCity;
static ArrayList<Forecast> weatherForecastList;
//WeatherAPI(String string) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
public class Forecast
{
String lowTemp;
String highTemp;
}
/**
*
* #param city
*/
public WeatherAPI(String city)
{
theCity = city;
theWeatherRSS = getWeatherAsRSS(city);
parseWeather(theWeatherRSS);
}
void parseWeather(String weatherHTML)
{
weatherForecastList = new ArrayList<Forecast>();
int startIndex = 0;
while(startIndex != -1)
{
startIndex = weatherHTML.indexOf("<yweather:forecast", startIndex);
if(startIndex != -1)
{ // found a weather forecast
int endIndex = weatherHTML.indexOf(">", startIndex);
String weatherForecast = weatherHTML.substring(startIndex, endIndex+1);
// get temp forecast
String lowString = getValueForKey(weatherForecast, "low");
String highString = getValueForKey(weatherForecast, "high");
Forecast fore = new Forecast();
fore.lowTemp = lowString;
fore.highTemp = highString;
weatherForecastList.add(fore);
// move to end of this forecast
startIndex = endIndex;
}
}
}
String getValueForKey(String theString, String keyString)
{
int startIndex = theString.indexOf(keyString);
startIndex = theString.indexOf("\"", startIndex);
int endIndex = theString.indexOf("\"", startIndex+1);
String resultString = theString.substring(startIndex+1, endIndex);
return resultString;
}
String getWeatherAsRSS(String city)
{
try{
/*
Adapted from: http://stackoverflow.com/questions/1381617/simplest-way-to-correctly-load-html-from-web-page-into-a-string-in-java
Answer provided by: erickson
*/
URL url = new URL("http://weather.yahooapis.com/forecastrss?w="+city+"&u=c");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
return(str);
}
catch(Exception e) {System.err.println("Weather API Exception: "+e);}
return null;
}
}
Thanks for any help, I am truly desperate because I have mixed up the dates of submission and I have not much time left....
Assuming label1 is your background label, just use label1.setIcon(...). What you will pass to it is a new ImageIcon
Also you haven't registered the ActionListener to your button. If you don't register a listener to the button, it won't do anything. Do this
button = new JButton("Check weather");
button.addActionListener(this);
add(button);
You haven't specified where the new image is coming from, so I really can't help you any further than this.

Why is my quizzcount doubling its value

I'm having a problem with this code in that the quizzcount variable is not outputting the correct value, it doubles the value.
I found a work around by diving the quizzcount by 2 and it works but i would really like to figure out why its doubling the value.
So for example, without dividing quizzcount by 2, if the user gets 7 out of the 10 questions correct the messagedialog will display that the user got 14 out of 10 correct.
What is causing this?
Thanks guys, any help would be appreciated.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;
import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Image;
import java.lang.*;
public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;
JRadioButton questA, questB, questC, questD, questE;
ButtonGroup questGroup;
JPanel questPanel;
JLabel question;
JPanel questionPanel;
JTextField resultText;
JLabel resultLabl;
JPanel resultPanel;
JButton nextButton;
JPanel quizPanel;
ImageIcon image;
JLabel imageLabl;
JPanel imagePanel;
JTextArea questionText;
JScrollPane scrollPane;
Random rand;
/** #param fileName is the desired name for the binary file. */
public MathFiles()
{
setTitle( "Math Quiz Competition" );
rand = new Random();
toFile = null;
//tracker = rand.nextInt(5)+1;
tracker = 1;
name = "Quiz"+tracker+".txt";
open = false;
//openFile(); //Use only when creating file
//writeMathsToTextFile(name);
setLayout( new FlowLayout() );
inputFile();
beginquiz();
showquestions();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end MathFiles constructor
/** Writes all Maths from a text file and writes them to a binary file.
#param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
Scanner inputFile = null;
Math nextMath = null;
String question_num;
String question;
String answera;
String answerb;
String answerc;
String answerd;
String answer_cor;
String file_name;
String SENTINEL ="DONE";
try
{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Text file " + fileName + " not found.");
System.exit(0);
}
Scanner keyboard = new Scanner(System.in);
System.out.print("Question number: ");
question_num = keyboard.nextLine();
while (!question_num.equalsIgnoreCase(SENTINEL))
{
System.out.print("Question: ");
question = keyboard.nextLine();
System.out.print("Answer A: ");
answera = keyboard.nextLine();
System.out.print("Answer B: ");
answerb = keyboard.nextLine();
System.out.print("Answer C: ");
answerc = keyboard.nextLine();
System.out.print("Answer D: ");
answerd = keyboard.nextLine();
fimage = rand.nextInt(30)+1;
file_name = "image"+fimage+".gif";
System.out.print(file_name);
System.out.print("Correct Answer: ");
answer_cor = keyboard.nextLine();
nextMath = new Math(question_num, question, answera, answerb,
answerc, answerd, answer_cor, file_name);
writeAnObject(nextMath);
numberOfMaths++;
System.out.print("\nQuestion number: ");
question_num = keyboard.nextLine();
} // end while
System.out.println("successfully created = " + name);
} // end readMathsFromTextFile
/** Opens the binary file for output. */
public void openFile()
{
try
{
FileOutputStream fos = new FileOutputStream(name);
toFile = new ObjectOutputStream(fos);
open = true;
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find, create, or open the file " + name);
System.out.println(e.getMessage());
open = false;
}
catch (IOException e)
{
System.out.println("Error opening the file " + name);
System.out.println(e.getMessage());
open = false;
}
//System.out.println("successfully opened = " + name);
} // end openFile
/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
try
{
if (open)
toFile.writeObject(anObject);
}
catch (InvalidClassException e)
{
System.out.println("Serialization problem in writeAnObject.");
System.out.println(e.getMessage());
System.exit(0);
}
catch (IOException e)
{
System.out.println("Error writing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end writeAnObject
public void result()
{
System.out.println("Your score is");
}
public void inputFile()
{
try
{
fromFile = new ObjectInputStream(new FileInputStream(name));
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end displayFile
/** Closes the binary file. */
public void closeFile()
{
System.out.println("closed name = " + name);
try
{
toFile.close();
open = false;
}
catch (IOException e)
{
System.out.println("Error closing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end closeFile
/** #return the fileís name as a string */
public String getName()
{
return name;
} // end getName
/** #return true if the file is open */
public boolean isOpen()
{
return open;
} // end isOpen
public void beginquiz()
{
try
{
aMath = (Math)fromFile.readObject();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
}
void showquestions()
{
//question group
/*question = new JLabel();
question.setText(aMath.getquestion());
question.setFont(new Font("Arial", Font.BOLD, 20));
question.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.add( question );*/
questionText = new JTextArea(5,20);
questionText.setWrapStyleWord(true);
questionText.setLineWrap(true);
questionText.setText(aMath.getquestion());
questionText.setFont(new Font("Arial", Font.BOLD, 20));
questionText.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
questionPanel.add( questionText );
// quest group
questA = new JRadioButton(aMath.getanswera(), false );
questB = new JRadioButton(aMath.getanswerb(), false );
questC = new JRadioButton(aMath.getanswerc(), false );
questD = new JRadioButton(aMath.getanswerd(), false );
questGroup = new ButtonGroup();
questGroup.add( questA );
questGroup.add( questB );
questGroup.add( questC );
questGroup.add( questD );
questPanel = new JPanel();
questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
questPanel.add( new JLabel("Choose the Correct Answer") );
questPanel.add( questA );
questPanel.add( questB );
questPanel.add( questC );
questPanel.add( questD );
// result panel
//resultText = new JTextField(20);
//resultText.setEditable( false );
//resultLabl = new JLabel("Result");
//resultPanel = new JPanel();
//resultPanel.add( resultLabl );
//resultPanel.add( resultText );
//button
nextButton = new JButton("Next");
quizPanel = new JPanel();
quizPanel.add(nextButton);
//Image image1 = new ImageIcon("image/image1.gif").getImage();
image = new ImageIcon("image1.gif");
imageLabl=new JLabel(image);
imagePanel = new JPanel();
imagePanel.add(imageLabl);
// frame: use default layout manager
add( imagePanel);
add( questionPanel);
add( questPanel);
//add( resultPanel);
questA.setActionCommand(aMath.getanswera());
questB.setActionCommand(aMath.getanswerb());
questC.setActionCommand(aMath.getanswerc());
questD.setActionCommand(aMath.getanswerd());
questA.addActionListener(this);
questB.addActionListener(this);
questC.addActionListener(this);
questD.addActionListener(this);
nextButton.setActionCommand( "next" ); // set the command
// register the buttonDemo frame
// as the listener for both Buttons.
nextButton.addActionListener( this );
add(quizPanel);
}
public void actionPerformed( ActionEvent evt)
{
//evt.getActionCommand() = aMath.getanswer_cor();
if (questA.isSelected()&&
aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questB.isSelected()&&
aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questC.isSelected()&&
aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questD.isSelected()&&
aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())
if ( evt.getActionCommand().equals( "next" ))
{
try
{
aMath = (Math)fromFile.readObject();
questionText.setText(aMath.getquestion());
questA.setText(aMath.getanswera());
questB.setText(aMath.getanswerb());
questC.setText(aMath.getanswerc());
questD.setText(aMath.getanswerd());
imageLabl.setIcon(new ImageIcon(aMath.getfile()));
questGroup.clearSelection();
repaint();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
if (count<=0)
count = 0;
else
count--;
JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
try{
Thread.sleep(2000);
System.exit(0);
}catch (InterruptedException em) { }
}
}
}
public static void main ( String[] args )
{
MathFiles mat = new MathFiles();
mat.setSize( 450, 550 );
mat.setLocationRelativeTo(null);
mat.setResizable( false );
mat.setVisible( true );
}
} // end MathFiles
class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;
public Math(String quesno, String quest, String ansa, String ansb, String ansc,
String ansd, String ans_cor, String file)
{
question_num = quesno;
question = quest;
answera = ansa;
answerb = ansb;
answerc = ansc;
answerd = ansd;
answer_cor = ans_cor;
file_name = file;
}
public void setquestion(String lName)
{
question = lName;
} // end setquestion
public void setquestion_num(String fName)
{
question_num = fName;
} // end setquestion_num
public void setanswera(String add)
{
answera = add;
} // end setanswera
public void setanswerb(String cty)
{
answerb = cty;
} // end setanswerb
public void setanswerc(String st)
{
answerc = st;
} // end setanswerc
public void setanswerd(String z)
{
answerd = z;
} // end setanswerd
public void setanswer_cor(String phn)
{
answer_cor = phn;
} // end setanswer_corr
public String getquestion_num()
{
return question_num;
} // end getquestion_num
/** #return the question */
public String getquestion()
{
return question;
} // end getquestion
/** #return the answera*/
public String getanswera()
{
return answera;
} // end getanswera
/** #return the answerb */
public String getanswerb()
{
return answerb;
} // end getanswerb
public String getanswerc()
{
return answerc;
} // end getanswerc
public String getanswerd()
{
return answerd;
} // end getanswerd
public String getanswer_cor()
{
return answer_cor;
} // end getanswer_corr
public String getfile()
{
return file_name;
} // end getanswer_corr
/** #return the Math information */
public String toString()
{
String myMath = getquestion_num() + " " + getquestion() + "\n";
myMath += getanswera() + "\n";
myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
myMath += getanswer_cor() + "\n";
myMath += getfile() + "\n";
return myMath;
} // end toString
} // end Math
It looks like your problem is that you've registered ActionListeners on the radio buttons. This means the event fires when you select an answer as well as clicking the 'next' button. With that in mind it should be obvious why your score is doubling itself.
As far as I can tell you don't need ActionListeners for the radio buttons. You should only be checking the answer when the user has indicated they are done with their selection. That the score is exactly doubling itself also suggests that you basically haven't tested the program besides naively selecting a radio button and clicking 'next'. Before commenting out the lines where you add the listeners to the radio buttons, try changing your answer. Open the program, select the correct answer, then select an incorrect answer, then select the correct answer again and click 'next'. See what happens.
This kind of error can also be easily found with a debugger. Just insert a breakpoint inside actionPerformed and it will be obvious it's being called by more than one action.

Java Multi-Client Chat Application - Sending messages issue

My problem is, I can still send messages between Clients(Client-to-Client) but after sending two or three times, messages are no more displayed to the recipient.
So basically whenever the Client wish to send a message to another Client, the message is first sent to the server. But as you have noticed from my coding, I am sending the server data in form of an object.
For example:
send(new ChatMessage(type, sender, content, recipient));
When you send a message the type is "message". When the server receives the object, it checks the receive data and its type.
For example:
ChatMessage cm = (ChatMessage) in[client[id].readObject();
if(cm.type.equals("message"){
send(findUserThread(toWhom), new ChatMessage("message", sender, content, recipient);
}
If the type is "message", then it sends that specific client the message.
I am using System.out.println() at the Client side to see the incoming data from server. So when I try to send some messages, it is working fine but then after sending some messages nothing is display on my chat screen.
According to my logic the errors can be:
1 Selected index in JList
2 Client[] array or username[] array
3 ObjectOutputStream and ObjectInputStream
ServerGUI class(Server Side)
package test2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.util.zip.GZIPOutputStream;
import javax.swing.SwingUtilities;
public class ServerGUI extends JFrame implements ActionListener {
public JList online;
private JTextField ipaddress, textMessage;
private JButton send, start, disconnect;
private JTextArea chatArea;
private JLabel port;
int client[] = new int[100];
private ObjectOutputStream out[] = new ObjectOutputStream[client.length + 1];
private ObjectInputStream in[] = new ObjectInputStream[client.length + 1];
String username[] = new String[client.length + 1];
static String b;
public String nm, usm;
private ServerSocket server;
private Socket connect;
boolean success = true;
int id = 0;
ArrayList<String> UserList = new ArrayList<String>();
public ServerGUI() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.setPreferredSize(new Dimension(650, 500));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.setBackground(Color.LIGHT_GRAY);
p.add(port = new JLabel("Port No"));
p.add(ipaddress = new JTextField("1500"));
p.add(start = new JButton("START"));
p.add(disconnect = new JButton("DISCONNECT"));
disconnect.setEnabled(false);
start.setBorderPainted(false);
start.setBackground(Color.blue);
start.setForeground(Color.WHITE);
disconnect.setBorderPainted(false);
disconnect.setBackground(Color.blue);
disconnect.setForeground(Color.WHITE);
ipaddress.setCaretPosition(0);
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.setBackground(Color.LIGHT_GRAY);
p1.add(chatArea = new JTextArea());
chatArea.setPreferredSize(new Dimension(300, 350));
chatArea.setLineWrap(true);
chatArea.setEditable(false);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.setBackground(Color.LIGHT_GRAY);
p2.add(textMessage = new JTextField(20));
p2.add(send = new JButton("SEND"));
send.setBackground(Color.blue);
send.setForeground(Color.WHITE);
send.setBorderPainted(false);
start.addActionListener(this);
send.addActionListener(this);
c.add(p, BorderLayout.NORTH);
c.add(p1, BorderLayout.CENTER);
c.add(p2, BorderLayout.SOUTH);
}
//current time
SimpleDateFormat log = new SimpleDateFormat("HH:mm");
String d = log.format(new Date());
//Start server
public void Start() {
int portNo = 0;
try {
String no = ipaddress.getText();
portNo = Integer.parseInt(no);
chatArea.append("Connection to port " + portNo + "...\n");
server = new ServerSocket(portNo);
success = true;
} catch (Exception ex) {
chatArea.append("Error cannot bind to port \n");
success = false;
}
if (success == true) {
addClient ob1 = new addClient("RunServer");
start.setEnabled(false);
disconnect.setEnabled(true);
}
}
public class addClient implements Runnable {
Thread t;
addClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
WaitClient();
} catch (Exception ex) {
break;
}
for (int i = 0; i < client.length; i++) {
if (client[i] == 0) {
client[i] = i + 1;
id = i;
break;
}
}
//set stream to send and receive data
out[client[id]] = new ObjectOutputStream(connect.getOutputStream());
out[client[id]].flush();
in[client[id]] = new ObjectInputStream(connect.getInputStream());
chatArea.append(d + " Client:[" + client[id] + "] : Connected successful \n");
chatArea.setCaretPosition(chatArea.getText().length());
//inform user that connection is successfull
ChatMessage cm = (ChatMessage) in[client[id]].readObject(); // read client username
if(cm.type.equals("login")){
chatArea.append("User " +cm.sender + " connected successfully" + "\n" );
username[client[id]] = cm.sender;
System.out.println(username[0]+ username[1]+ username[2]);
send(client[id], new ChatMessage("login", username[client[id]], "user", "SERVER"));
sendUserList(cm.sender);
Announce("newuser", "SERVER", cm.sender);
}
Chat c = new Chat(client[id], "StartChat" + client[id]); // make new thread for every new client
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Chat implements Runnable {
int id1;
Chat ob1;
Thread t;
Chat(int id1, String info1) {
this.id1 = id1; // create a thread for client
t = new Thread(this, info1);
t.start();
}
public void run() {
boolean running = true;
while(running){
try {
ChatMessage cm = (ChatMessage) in[client[id]].readObject(); // read client username
if(cm.type.equals("message")){
send(findUserThread(cm.recipient), new ChatMessage(cm.type, cm.sender, cm.content, cm.recipient));
}
} catch (Exception e) {
}
}
}
}
//wait for connection, then display connection information
private void WaitClient() throws IOException {
chatArea.append(d + " : Waiting for connection... \n");
connect = server.accept();
chatArea.append(d + " : Now connected to " + connect.getInetAddress().getHostName() + "\n");
}
//send message to specific user
public void sendUser(int number, String info) {
try {
out[number].writeObject(info);
out[number].flush();
} catch (Exception e) {
}
}
public void sendServer(String por) {
for (int i = 0; i < client.length; i++) // for loop trying to send message from server to all clients
{
if (client[i] != 0) // this line stop server to send messages to offline clients
{
try {
out[i + 1].writeObject(por);
out[i + 1].flush();
} catch (Exception e) {
}
}
}
}
public void Announce(String type, String sender, String content){
ChatMessage cm = new ChatMessage(type, sender, content, "All");
for(int i = 0; i < id; i++){
send(client[i], cm);
}
}
public void send(int number, ChatMessage cm) {
try {
out[number].writeObject(cm);
out[number].flush();
} catch (Exception e) {
}
}
void sendAll(int num, String por) {
for (int i = 0; i < client.length; i++) // for loop trying to send message from server to all clients
{
if (client[i] != 0) // this line stop server to send messages to offline clients (if "clientNiz[X] = 0" don't try to send him message, because that slot is empty)
{
if (num != i + 1) // don't repeat messages (when for ex. client_1 send message to all clients, this line stop server to send same message back to client_1)
{
try {
out[i + 1].writeObject(por);
out[i + 1].flush();
} catch (Exception e) {
}
}
}
}
}
public void sendUserList(String toWhom){
for(int i = 0; i <= id; i++){
send(findUserThread(toWhom), new ChatMessage("newuser", "SERVER", username[client[i]], toWhom));
}
}
public int findUserThread(String usr){
for(int i = 0; i <= id; i++){
if(username[client[i]].equals(usr)){
return client[i];
}
}
return -1;
}
private int findClient(int num){
for (int i = 0; i <= id; i++){
if (client[i] == (num+1)){
return i;
}
}
return -1;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == send) {
//current time
String s1 = textMessage.getText();
send(client[id], new ChatMessage("message", "admin", s1, "client"));
chatArea.append("Administrator: " + s1 + "\n");
} else if (e.getSource() == start) {
Start();
}
if (e.getSource() == disconnect) {
try {
server.close();
} catch (Exception ex) {
}
for (int i = 0; i < client.length; i++) {
try {
in[i].close();
out[i].close();
} catch (Exception ex) {
}
}
chatArea.append("Server is disconnected\n");
start.setEnabled(true);
disconnect.setEnabled(false);
}
}
}
MainGUI class(Client Side)
package test2;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
public class MainGUI extends javax.swing.JFrame {
public MainGUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
start = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
textMessage = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
chatArea = new javax.swing.JTextArea();
usernm = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
send = new javax.swing.JButton();
upload = new javax.swing.JButton();
filename = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
online = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("ICARE ");
setFocusable(false);
setPreferredSize(new java.awt.Dimension(840, 650));
setResizable(false);
getContentPane().setLayout(null);
jButton1.setText("Video Call");
getContentPane().add(jButton1);
jButton1.setBounds(270, 10, 100, 30);
jButton3.setText("Send");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(690, 100, 100, 30);
start.setBackground(new java.awt.Color(51, 51, 255));
start.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
start.setForeground(new java.awt.Color(255, 255, 255));
start.setText("Start");
start.setBorder(null);
start.setBorderPainted(false);
start.setRequestFocusEnabled(false);
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
}
});
getContentPane().add(start);
start.setBounds(630, 50, 90, 40);
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 0, 820, 0);
getContentPane().add(textMessage);
textMessage.setBounds(270, 450, 420, 70);
chatArea.setColumns(20);
chatArea.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
chatArea.setRows(5);
jScrollPane2.setViewportView(chatArea);
getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(270, 140, 520, 300);
getContentPane().add(usernm);
usernm.setBounds(450, 60, 170, 30);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Enter your nickname:");
getContentPane().add(jLabel1);
jLabel1.setBounds(270, 60, 150, 30);
send.setBackground(new java.awt.Color(51, 51, 255));
send.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
send.setForeground(new java.awt.Color(255, 255, 255));
send.setText("Send");
send.setBorder(null);
send.setBorderPainted(false);
send.setRequestFocusEnabled(false);
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendActionPerformed(evt);
}
});
getContentPane().add(send);
send.setBounds(700, 470, 90, 40);
upload.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
upload.setText("+");
upload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uploadActionPerformed(evt);
}
});
getContentPane().add(upload);
upload.setBounds(633, 100, 50, 30);
getContentPane().add(filename);
filename.setBounds(270, 100, 350, 30);
jScrollPane1.setViewportView(online);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(30, 20, 220, 500);
pack();
}// </editor-fold>
private void startActionPerformed(java.awt.event.ActionEvent evt) {
Start();
}
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String z = textMessage.getText();
String target = online.getSelectedValue().toString();
chatArea.append("[ " + usernm.getText() + " ] : " + z + "\n");
send(new ChatMessage("message", usernm.getText(), z, target));
textMessage.setText("");
}
private void uploadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Create a file chooser
//In response to a button click:
JFileChooser fileChooser = new JFileChooser();
fileChooser.showDialog(this, "Select File");
file = fileChooser.getSelectedFile();
if(file != null){
if(!file.getName().isEmpty()){
String str;
if(filename.getText().length() > 30){
String t = file.getPath();
str = t.substring(0, 20) + " [...] " + t.substring(t.length() - 20, t.length());
}
else{
str = file.getPath();
}
filename.setText(str);
}
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
long size = file.length();
if(size < 120 * 1024 * 1024){
sendUser("download");
}
else{
chatArea.append("File is size too large\n");
}
}
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(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainGUI.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 MainGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JTextArea chatArea;
private javax.swing.JTextField filename;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
public javax.swing.JList online;
private javax.swing.JButton send;
private javax.swing.JButton start;
private javax.swing.JTextField textMessage;
private javax.swing.JButton upload;
private javax.swing.JTextField usernm;
// End of variables declaration
private ObjectOutputStream out;
private ObjectInputStream in;
static String b; //variable for message
private Socket join;
boolean success = true;
private String serverIP = "127.0.0.1"; //set IP Address
ArrayList<String> userlist = new ArrayList<String>(); //ArrayList to store online users
//current time
SimpleDateFormat log = new SimpleDateFormat("HH:mm");
String d = log.format(new Date());
public File file;
public DefaultListModel model = new DefaultListModel();
//Start client program
public void Start() {
try {
start.setEnabled(false);
chatArea.append(d + " : Attempting connection... \n");
join = new Socket(serverIP, 10500);
chatArea.append(d + " : Connected to - " + join.getInetAddress().getHostName() + "\n");
success = true;
} catch (Exception ex) {
chatArea.append("Error cannot bind to port \n");
success = false;
}
if (success == true) {
ClientThread ct = new ClientThread();
}
}
class ClientThread implements Runnable {
ClientThread ct;
Thread t;
ClientThread() {
t = new Thread(this, "RunClient");
t.start();
}
public void run() {
try {
try {
out = new ObjectOutputStream(join.getOutputStream());
out.flush();
in = new ObjectInputStream(join.getInputStream());
send(new ChatMessage("login", usernm.getText(), "password", "SERVER"));
} catch (Exception e) { }
CThread c1 = new CThread();
} catch (Exception ex) { }
}
}
class CThread implements Runnable {
CThread ob1;
Thread t;
CThread() {
t = new Thread(this, "Message");
t.start();
}
public void run() {
boolean running = true;
try {
while(running){
try {
ChatMessage cm = (ChatMessage) in.readObject();
System.out.println("Incoming :" + cm.toString());
if(cm.type.equals("login")){
chatArea.append(cm.sender + " is online" + "\n");
}else if(cm.type.equals("message")){
if(cm.recipient.equals(usernm.getText())){
chatArea.append("[ "+cm.sender +" ] : " + cm.content + "\n");
}
}else if(cm.type.equals("newuser")){
online.setModel(model);
model.addElement(cm.content);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
}
}
}
void sendUser(String por) {
try {
out.writeObject(por);
out.flush();
} catch (Exception e) {
}
}
void send(ChatMessage cm){
try {
out.writeObject(cm);
out.flush();
} catch (Exception e) {
}
}
}
ChatMessage class
package test2;
import java.io.Serializable;
public class ChatMessage implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public ChatMessage(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}
ServerTest to run ServerGUI
public class ServerTest
{
public static void main(String args[]){
ServerGUI m = new ServerGUI();
m.setTitle("Server");
m.setVisible(true);
m.pack();
//to make to the center of the screen
m.setLocationRelativeTo(null);
}
}
Classes in Java should start with uppercase. For example: ServerGUI but not addClient as seen in your code.
Classes represent objects. Or "classes" of objects. For example Car or ServerGUI but not addClient. What is an new addClient()? Is that an object really?
Variable names should have significant names if possible. For example Car limousine = new Car(4,Color.Black) and not addClient ob1 = new addClient("RunServer"). What does ob1 mean?
Comments are fresh air for readers. Please, use comments. For example: //we are going to represent the server as a special user with admin privileges
Method names ir Java should not start with uppercase. This is a bad example: private void WaitClient() throws IOException
Indent and blank lines. Don't know if it is your fault partly or completely but the code is bad indented, has blank lines inside blocks (not just one or two, nor acting as separator), and misses spaces (if(cm.type.equals("login")){)
StackOverflow is not a good place for your problem. Here people ask specific questions. Yours is not a specific question, it is more a "my program doesn't work" problem.
In conclusion: your code is hard to read and understand. It seems you are new to Java so please, start with simple and easy examples, use a Java IDE like Eclipse or Netbeans and take your time! You won't learn Java in a week, be patient.
Sorry if I've been too honest but that's what I think (and probably one of the reasons nobody else here is helping you).
But after sending two or three messages, my program stop sending messages
First of all you should try to debug your application. Using logs or System.out.println you can easily find out where is it "stopping". Is the message being sent to the server? Is the server sending the message to the client? You can answer these questions with just a few println.
Once you know where (in your code, which method) it is failing you can post a more specific question if you still need help.
Also when you have a problem, please explain what problem it is really, in detail. Does the application crash? Does it stop sending messages to everybody? "my program stops sending messages" is a little bit vague.
EDIT: Well, now that I see the code, please, do not do this:
void send(ChatMessage cm){
try {
out.writeObject(cm);
out.flush();
} catch (Exception e) {
}
}
If an exception is thrown, you won't notice.
You should add:
e.printStackTrace();
inside every catch() block so you can see errors in console when they occur.
Nobody likes red messages in console, but hiding them is not going to help. Always print errors, or log them, or both :)

Categories