UDP Client/Server Calulator with GUI - java

UDP Client/Server Application
I am having hard times completing the given above. I successfully created the interface but my main issues are sending the numbers and the operation from the client class to the server and then sending the final answer back to the client. Can someone please give me an advice what should I do next.
//Client.Java
import java.swing.*;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Client {
public static void main(String[] args) throws IOException {
DatagramSocket clientSocket = new DatagramSocket ();
//Connect to server
InetAddress ipAddress = InetAddress.getByName("localhost"); //12.0.0.1
int portNumber = 9876;
//Calculator Frame
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Calculator Assignment" );
frame.getContentPane().setLayout(null);
frame.setVisible(true);
//Label
JLabel label = new JLabel("");
label.setBounds(20, 20, 200, 20);
label.setFont(new Font("Times", Font.BOLD, 16));
label.setHorizontalAlignment(SwingConstants.LEFT);
label.setVerticalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(label);
//First Number Label
JLabel label1 = new JLabel("");
label1.setBounds(20, 20, 200, 20);
label1.setFont(new Font("Times", Font.BOLD, 13));
label1.setHorizontalAlignment(SwingConstants.LEFT);
label1.setVerticalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(label1);
label1.setText("First Number");
//Text Field
JTextField textfield1= new JTextField("");
textfield1.setFont(new Font("Times", Font.BOLD, 14));
textfield1.setBounds(140, 20, 150, 20);
frame.getContentPane().add(textfield1);
//Second Number Label
JLabel label2 = new JLabel("");
label2.setBounds(20, 40, 200, 20);
label2.setFont(new Font("Times", Font.BOLD, 13));
label2.setHorizontalAlignment(SwingConstants.LEFT);
label2.setVerticalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(label2);
label2.setText("Second Number");
//Text Field
JTextField textfield2= new JTextField("");
textfield2.setFont(new Font("Times", Font.BOLD, 14));
textfield2.setBounds(140, 40, 150, 20);
frame.getContentPane().add(textfield2);
//"Answer" Label
JLabel label3 = new JLabel("");
label3.setBounds(20, 70, 200, 20);
label3.setFont(new Font("Times", Font.BOLD, 13));
label3.setHorizontalAlignment(SwingConstants.LEFT);
label3.setVerticalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(label3);
label3.setText("Answer: ");
//Buttons
JButton button1 = new JButton("+");
button1.setBounds(20, 120, 60, 23);
frame.getContentPane().add(button1);
JButton button2 = new JButton("-");
button2.setBounds(85, 120, 60, 23);
frame.getContentPane().add(button2);
JButton button3 = new JButton("×");
button3.setBounds(150, 120, 60, 23);
frame.getContentPane().add(button3);
JButton button4 = new JButton("÷");
button4.setBounds(215, 120, 60, 23);
frame.getContentPane().add(button4);
JButton button5 = new JButton("Max");
button5.setBounds(280, 120, 60, 23);
frame.getContentPane().add(button5);
JButton button6 = new JButton("Min");
button6.setBounds(345, 120, 60, 23);
frame.getContentPane().add(button6);
//Buttons Actions
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText( "Answer: "+ textfield1.getText() + " + " + textfield2.getText() + " = " + receivedAnswer );
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText( "Answer: "+ textfield1.getText() + " - " + textfield2.getText() + " = " + receivedAnswer );
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText( "Answer: "+ textfield1.getText() + " x " + textfield2.getText() + " = " + receivedAnswer);
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText( "Answer: "+ textfield1.getText() + " ÷ " + textfield2.getText() + " = " + receivedAnswer);
}
});
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText("Answer: Maximum is: " + receivedAnswer);
}
});
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label3.setText("Answer: Minimum is: " + receivedAnswer);
}
});
//Send First Number
String sendingFirst = textfield1.getText();
byte[] SendingFirst = new byte[1024];
SendingFirst = sendingFirst.getBytes();
DatagramPacket sendingPacket1 = new DatagramPacket(SendingFirst, SendingFirst.length, ipAddress, portNumber);
clientSocket.send(sendingPacket1);
//Send Second Number
String sendingSecond = textfield2.getText();
byte[] SendingSecond = new byte[1024];
SendingSecond = sendingSecond.getBytes();
DatagramPacket sendingPacket2 = new DatagramPacket(SendingSecond, SendingSecond.length, ipAddress, portNumber);
clientSocket.send(sendingPacket2);
//Receive reply from server
byte[] receivedData = new byte[1024];
DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
clientSocket.receive(receivedPacket);
String receivedAnswer = new String(receivedPacket.getData());
System.out.println(receivedAnswer);
clientSocket.close();
}
}
//Server.Java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server {
public static void main(String[] args) {
try {
//creating a UDP socket with a port number
DatagramSocket serverSocket = new DatagramSocket(9876);
while (true) {
//Create empty datagrams
byte[] receivedData = new byte[1024];
DatagramPacket receivedPacket1 = new DatagramPacket(receivedData, receivedData.length);
DatagramPacket receivedPacket2 = new DatagramPacket(receivedData, receivedData.length);
//receive from the network through the socket and fill in the empty datagrams
serverSocket.receive(receivedPacket1);
serverSocket.receive(receivedPacket2);
//extract data and print it
String receivedFirst = new String(receivedPacket1.getData());
System.out.println(receivedFirst);
String receivedSecond = new String(receivedPacket1.getData());
System.out.println(receivedSecond);
//Arithmetic Computation and finding Min/Max
float first = Integer.parseInt(receivedFirst);
float second = Integer.parseInt(receivedSecond);
float add, subtract, multiply, divide, maximum, minimum;
add = first + second;
subtract = first - second;
multiply = first * second;
divide = (float) first / second;
if (first > second) {
maximum = first;
minimum = second;
}
else if(second > first) {
maximum = second;
minimum = first;
}
else {
maximum = first;
minimum = first;
}
//reply to the client that sent the message
InetAddress ipAddress = receivedPacket1.getAddress();
int portNumber = receivedPacket1.getPort();
String sendingSentence = "Hello from Server";
byte[] SendingData = new byte[1024];
SendingData = sendingSentence.getBytes();
DatagramPacket sendingPacket = new DatagramPacket(SendingData, SendingData.length, ipAddress, portNumber);
serverSocket.send(sendingPacket);
serverSocket.close();
}
}
catch (Exception ex) {
}
}
}

Related

how to create an onscreen keyboard for a program in java eclipsee

For my school project i need to create a bank simulator.so as a first step i am supposed to show an on screen keyboard when a button is clicked on the keyboard that value should go to the text boxes.I am totally blank. i tried i could create the keyboard. its in a different frame.so i do not know how to retrieve data from it when the buttons are clicked on it.please help guys.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class BankSimulator extends JFrame implements ActionListener {
JTextField username = new JTextField(10);
JTextField password = new JTextField(10);
JTextField name = new JTextField(10);
JTextField setPassword = new JTextField(5);
JLabel userlbl = new JLabel("Username");
JLabel passlbl = new JLabel("Password");
JRadioButton option1 = new JRadioButton("Basic Account");
JRadioButton option2 = new JRadioButton("Saver Account");
JRadioButton option3 = new JRadioButton("Super Account");
JButton logbtn = new JButton("Log In");
JButton regbtn = new JButton("Register");
JButton showkeyboard = new JButton("showkeyboard");
JButton createbtn = new JButton("Create Account");
JButton[] btn1 = new JButton[10];
JButton[] btn2 = new JButton[10];
JButton[] btn3 = new JButton[9];
JButton[] btn4 = new JButton[7];
public static void main(String[] args) {
BankSimulator bm = new BankSimulator();
}
public BankSimulator() {
setLayout(null);
setSize(850, 700);
setTitle("Bank Simulator");
username.setBounds(350, 150, 130, 20);
add(username);
password.setBounds(350, 180, 130, 20);
add(password);
option1.setBounds(440, 180, 130, 20);
option2.setBounds(440, 210, 130, 20);
option3.setBounds(440, 240, 130, 20);
add(option1);
add(option2);
add(option3);
option1.setVisible(false);
option2.setVisible(false);
option3.setVisible(false);
name.setBounds(440, 150, 130, 20);
add(name);
name.setVisible(false);
setPassword.setBounds(440, 123, 130, 20);
add(setPassword);
setPassword.setVisible(false);
userlbl.setBounds(288, 150, 130, 20);
add(userlbl);
passlbl.setBounds(288, 180, 130, 20);
add(passlbl);
logbtn.setBounds(341, 220, 150, 30);
add(logbtn);
createbtn.setBounds(435, 270, 150, 30);
add(createbtn);
createbtn.setVisible(false);
logbtn.addActionListener(this);
regbtn.setBounds(341, 260, 150, 30);
add(regbtn);
regbtn.addActionListener(this);
showkeyboard.setBounds(341, 270, 150, 30);
add(showkeyboard);
showkeyboard.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showkeyboard();
}
});
setVisible(true);
}
public void showkeyboard() {
String nos = "1234567890";
String alphabet = "abcdefghij";
String alphabet1 = "klmnopqrs";
String alphabet2 = "tuvwxyz";
JFrame myFrame = new JFrame();
myFrame.setSize(586, 205);
JPanel myPanel = new JPanel();
JPanel myPanel1 = new JPanel();
JPanel myPanel2 = new JPanel();
JPanel myPanel3 = new JPanel();
for (int i = 0; i < nos.length(); i++) {
btn1[i] = new JButton(nos.substring(i, i + 1));
myPanel.add(btn1[i]);
btn1[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
keyboardButtonPressed();
}
});
for (int i = 0; i < alphabet.length(); i++) {
btn2[i] = new JButton(alphabet.substring(i, i + 1));
myPanel1.add(btn2[i]);
}
for (int i = 0; i < alphabet1.length(); i++) {
btn3[i] = new JButton(alphabet1.substring(i, i + 1));
myPanel2.add(btn3[i]);
}
for (int i = 0; i < alphabet2.length(); i++) {
btn4[i] = new JButton(alphabet2.substring(i, i + 1));
myPanel3.add(btn4[i]);
}
JPanel outer = new JPanel();
outer.add(myPanel);
outer.add(myPanel1);
outer.add(myPanel2);
outer.add(myPanel3);
myFrame.add(outer);
myFrame.setVisible(true);
}
}
public String keyboardButtonPressed(char a) {
String alreadyDisplayed = username.getText();
String toDisplay = alreadyDisplayed + btn1[i].getText();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == regbtn) {
username.setVisible(false);
password.setVisible(false);
logbtn.setVisible(false);
userlbl.setVisible(false);
passlbl.setVisible(false);
option1.setVisible(true);
option2.setVisible(true);
option3.setVisible(true);
name.setVisible(true);
setPassword.setVisible(true);
regbtn.setVisible(false);
createbtn.setVisible(true);
}
}
}
btn[i].getText() is not working saying the 'i' cannot be resolved to a variable.
So, your basic problem is one of context...
for (int i = 0; i < nos.length(); i++) {
//...
for (int i = 0; i < alphabet.length(); i++) {
//...
}
for (int i = 0; i < alphabet1.length(); i++) {
//...
}
for (int i = 0; i < alphabet2.length(); i++) {
//...
}
Basically, i is already defined in the outer loop, so you can't re-use it

Can't fix NullPointerException with JTextArea [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a text based adventure that runs in a jframe but when i run the program i get a NullPointer error on line 97 (first time i append console in the game method) and I have no idea how to fix it. I am relatively new to java so its probably something simple that I just don't know.
my code is here
package window;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Gui extends JFrame {
public JPanel contentPane;
public static JTextField input;
public static JButton send;
public static JTextArea console;
public static JTextArea invintory;
public static JTextArea stats;
static String i = "";
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
JTextArea stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
JTextArea invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
JButton send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
public static void game (JButton send, JTextArea console, JTextArea stats, JTextArea invintory, JTextField input, String i) {
//start
//START
//START
//START
//START
while (true) {
console.append("You wake up open feild, with vast amounts of wheet in every direction");
console.append("There is a path going in either direction what do you want to do");
console.append("\t1. Go left.");
console.append("\t2. Go right.");
while (i == "") {
}
if (i == "1") {
console.append("1");
break;
}
else if (i == "2") {
console.append("2");
break;
}
}
//END
//END
//END
//END
}
public static void main(String[] args) {
try {
Gui frame = new Gui();
frame.setVisible(true);
Gui.game(send, console, stats, invintory, input, i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your global variable console is null
public static JTextArea console;
You initialized it in Gui method
JTextArea console = new JTextArea();
So here in Gui method your global console variable is not initialized, This creates a local variable console under Gui method.
To initialize global variable in Gui method you need to initialize this way
console = new JTextArea();
You did this mistake to all variables so edit your code this way
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}

Run method never get executed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently trying to develop a simple local area network chat feature for the company. But I'm stuck at this point where the run method never get executed in client which previously working fine. It started not working after I restructure the constructor to be able to dispose and visible frame on system tray icon double click. Please let me know where I'm go wrong. I send you the code where it was previously working and current now where it's not working. I can also send the server interface source and other code if needed.
Before structuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
public class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JFrame frame;
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_1, area_2;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
ChatClient(String name, String IP, Login login) {
super(name);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
this.name = name;
this.login = login;
frame = new JFrame("Client - " + name);
frame.setIconImage(bd);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
area_1 = new JTextArea(20, 10);
area_1.setFont(login.notify);
area_1.setLineWrap(true);
area_1.setEditable(false);
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
scroll = new JScrollPane(area_1);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
mainPanel.setLayout(new BorderLayout());
listModel = new DefaultListModel();
list = new JList(listModel);
list.setToolTipText("Client available");
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
frame.getContentPane().add(mainPanel);
mainPanel.add(menuBar);
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(list);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(login.notify);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(80, 360, 150, 15);
charCnt.setFont(small);
scroll.setBounds(5, 30, 390, 300);
scroll2.setBounds(5, 335, 450, 35);
list.setBounds(400, 30, 185, 260);
field_2.setBounds(479, 300, 110, 25);
cb1.setBounds(398, 300, 70, 20);
//button
button_1.setBounds(490, 336, 95, 27);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
thr.start();
} catch (IOException e) {
area_1.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
this.frame.dispose();
System.exit(0);
}
area_2.requestFocus();
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {createAndShowUI(); >>this code here executed properly.
} catch (IOException | HeadlessException e) {
JOptionPane.showMessageDialog(null, "Server has Closed!" + lineSeparator + "Sorry, you've to log out");
System.exit(0);
}
}
After restructuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public final class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_2;
JTextPane chatPane;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2, scroll3;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
Font prv = new Font("Helvetica", Font.ITALIC, 14);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
/**
*
* #param name
* #param IP
* #param login
*/
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
public ChatClient(String name, String IP, Login login) {
super(name);
try {
createAndShowUI(name);
createAndShowGUI(name);
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
} catch (IOException e) {
chatPane.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
System.exit(0);
}
}
public ChatClient() {
// defaultItem1.addActionListener(exitListener);
// defaultItem2.addActionListener(restoreListener);
// this.login = login;
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
chatPane = new JTextPane();
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
listModel = new DefaultListModel();
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setToolTipText("Client available");
list.setVisibleRowCount(5);
scroll = new JScrollPane(chatPane);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
scroll2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll3 = new JScrollPane(list);
scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.setLayout(new BorderLayout());
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(scroll3);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(prv);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(380, 358, 120, 15);
charCnt.setFont(small);
scroll.setBounds(5, 25, 390, 300);
//chatPane.setFocusable(false);
chatPane.setEditable(false);
scroll2.setBounds(5, 325, 485, 48);
scroll3.setBounds(400, 30, 185, 260);
field_2.setBounds(477, 300, 112, 25);
cb1.setBounds(398, 300, 70, 20);
button_1.setBounds(490, 326, 100, 30);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
thr.start();
} catch (Exception e) {
}
area_2.requestFocus(true);
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {
createAndShowUI(); >> this code never run to
Login.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
final class Login {
JFrame frame;
JPanel panel;
JLabel label_1, label_2, label_3, label_4;
JTextField field_1, field_2;
JPasswordField pass;
JButton button_1, button_2;
Font Default = new Font("Comic Sans MS", Font.PLAIN, 12);
Font notify = new Font("Comic Sans MS", Font.BOLD, 12);
Font small = new Font("Sans Serif", Font.ITALIC, 3);
//String IP;
Socket client;
InetAddress ipaddr;
String hostname;
PrintStream toServer;
ChatClient clientObj;
public String gethostString(){
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
}
catch (UnknownHostException e) {
}
return hostname;
}
#SuppressWarnings("CallToPrintStackTrace")
Login() {
String IP = "192.168.10.88";
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
clientObj = new ChatClient(gethostString(), IP, this);
// clientObj.createAndShowGUI(hostname);
// clientObj.createAndShowUI();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Image bd = Toolkit.getDefaultToolkit().getImage("Image/login.png");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
}
}
This is my method createAndShowUI.
public void createAndShowUI(String name) {
this.name = name;
JFrame frame;
frame = new JFrame("Client - " + name);
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
frame.setIconImage(bd);
frame.getContentPane().add(new ChatClient().mainPanel); >> I call the constructor here to draw the frame.
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setSize(600, 400);
frame.setResizable(false);
// frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JComponent getComponent() {
return mainPanel;
}
Any help would be very much appreciated. Cheers!
You created a second no-argument constructor, and nobody is invoking that second constructor. However, you moved the code that starts the thread into that second constructor, so now the thread is not being started anymore().
Perhaps you want to call this method public void init() { instead of public ChatClient() {, and then you call init(); at the end of the first constructor that has 3 arguments.

Two way communication between GUI and a Server Client

I'm trying to send a certain string when a button is pressed in my GUI. My Client class is currently running to keep taking string commands from the command line and send them to the server where they will be processed and a response will be returned.
How can I now send the data through my GUI and move the results back to my GUI?
E.g. I have a button called "pickup" which, when clicked will send the string "PICKUP" to the server, through the Client class.
Likewise, the response from the server would be either "SUCCESS" or "FAIL" which would be printed through the Thread "serverResponse" in my Client class and this needs to somehow be sent to an arbitrary method in the playerGUI class as a parameter.
Thanks for any help, sorry for not using the conventional class/method/field naming styles!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class playerGUI {
private JFrame frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private static Client newclient;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.frame.setVisible(true);
newclient = new Client(GUI);
}
/**
* Create the application.
*/
public playerGUI() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 500, 630);
frame.setUndecorated(false); // REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 630);
humanGameWindow.setVisible(false);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I WANT TO SEND THE STRING "PICKUP" TO WHERE THE STARS ARE IN Client.class
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
JButton Look = new JButton("Look");
Look.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
Look.setBackground(new Color(100, 149, 237));
Look.setBounds(40, 514, 100, 40);
humanGameWindow.add(Look);
humanGameWindow.add(pickup);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.DARK_GRAY);
mainMenu.setBounds(0, 0, 500, 630);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
JButton mainMenuQuit = new JButton("Quit");
mainMenuQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mainMenuQuit.setBackground(new Color(100, 149, 237));
mainMenuQuit.setBounds(220, 345, 70, 55);
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
frame.getContentPane().add(humanGameWindow);
frame.getContentPane().add(mainMenu);
frame.setVisible(true);
}
}
This is the Client class, the thread is where I want to send the response to the GUI class to process and display a specific output. The asterisks is where I want to send the text from button presses in the GUI class (there are other buttons I have deleted the code for easier reading!).
import java.net.*;
import java.io.*;
public class Client{
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//I WANT TO SEND "response" TO THE GUI CLASS
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
String sending = *************************
//String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}

JAVA two way communication between classes

I want to be able to create an instance of my Client class in my GUI and then pass GUI.this as a parameter for the Client constructor but I'm not sure exactly how to do that. I know I'm missing something obvious! I want to be able to call methods on the other from either class. Obviously I have commented code out because I don't know how or what I am supposed to do to achieve this two way communication without merging the classes! I want to be able to do stuff like send a command through the Client from the GUI class when the "Up" button is clicked on the GUI etc. Thanks for the help in advance.
Client class:
public class Client{
//static playerGUI GUI;
public static void main(String[] args) {
//GUI = new playerGUI();
//GUI.getFrame().setVisible(true);
//Client cli = new Client("localhost",4444);
}
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//GUI.processgrid(response);
//send to GUI to process output!
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
//inputbuttons!
String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
GUI Class:
public class playerGUI {
private JFrame Frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private playerGUI GUI;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(this.playerGUI);
}
/**
* Create the application.
*/
public playerGUI() {
Frame.getContentPane().setBackground(new Color(255, 255, 255));
Frame.getContentPane().setLayout(null);
Frame.setBounds(100, 100, 500, 630);
Frame.setUndecorated(false); // REMOVES MENU BAR
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ############################################################################################################################################################################
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 600);
humanGameWindow.setVisible(false);
JLabel gameTitle = new JLabel("DUNGEON OF DOOM!!");
gameTitle.setForeground(new Color(100, 149, 237));
gameTitle.setFont(new Font("Moire", Font.BOLD, 28));
gameTitle.setBounds(92, 5, 380, 50);
JButton up = new JButton("Up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
up.setBackground(new Color(100, 149, 237));
up.setBounds(274, 514, 100, 40);
JButton down = new JButton("Down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
down.setBackground(new Color(100, 149, 237));
down.setBounds(274, 555, 100, 40);
JButton left = new JButton("Left");
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
left.setBackground(new Color(100, 149, 237));
left.setBounds(173, 535, 100, 40);
JButton right = new JButton("Right");
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
right.setBackground(new Color(100, 149, 237));
right.setBounds(375, 535, 100, 40);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
JButton Exit = new JButton("Exit");
Exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Exit.setBackground(new Color(100, 149, 237));
Exit.setBounds(427, 17, 70, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
humanGameWindow.add(gameTitle);
humanGameWindow.add(up);
humanGameWindow.add(down);
humanGameWindow.add(left);
humanGameWindow.add(right);
humanGameWindow.add(pickup);
humanGameWindow.add(Exit);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.LIGHT_GRAY);
mainMenu.setBounds(0, 0, 500, 600);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
hostTextPane = new JTextPane();
hostTextPane.setToolTipText("Enter the host name");
hostTextPane.setBackground(new Color(192, 192, 192));
hostTextPane.setBounds(50, 100, 234, 30);
hostTextPane.setFont(new Font("Moire", Font.BOLD, 19));
portTextPane = new JTextPane();
portTextPane.setToolTipText("Enter the port");
portTextPane.setBackground(new Color(192, 192, 192));
portTextPane.setBounds(50, 175, 234, 30);
portTextPane.setFont(new Font("Moire", Font.BOLD, 19));
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
//not sure if i need to be creating the Client here?
/*
* if (!(hostTextPane.getText().equals("")) &&
* !(portTextPane.getText().equals(""))) { try { Client cli =
* new Client(hostTextPane.getText(), Integer
* .parseInt(portTextPane.getText())); } catch (Exception e1) {
* System.out.println("Error."); } } else {
* JOptionPane.showMessageDialog(null,
* "Do not leave hostname or port no. blank."); }
*/
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
mainMenu.add(hostTextPane);
mainMenu.add(portTextPane);
getFrame().getContentPane().add(humanGameWindow);
getFrame().getContentPane().add(mainMenu);
getFrame().setVisible(true);
}
}
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(GUI);
}
main is a static method, which means it is run in a static context (ie, not "as" any instantiated object). This means you can't access this in main because there is no this to access. You need to access playerGUI with just playerGUI or playerGUI.playerGUI in your Client.main method. Also, you need to set the field playerGUI.playerGUI to static.
Instead of this:
Client newclient = new Client(this.playerGUI);
you need this:
Client newclient = new Client(GUI);
Notice that as main is static there is no this defined.
Also consider changing the names of your class and variables to follow Java naming conventions:
playerGUI should be PlayerGUI
GUI should be gui or whatever you feel like but starting with lowercase
Also do you notice that you are not using that field called GUI? You are only using the variable GUI. So it may be adding up to the confusion.

Categories