NullPointException when I try to navigate forms on j2me using buttons - java

I'm having trouble linking the main page to the second page by the click of a button. It throws a NullPointException. Can someone please tell me where I've erred?
import java.io.InputStream;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class standings extends MIDlet implements ActionListener{
public Command cmdSelect;
public Form fform, selectLgform;
public Button btnSelectLeague,btnHelp,btnAbout,btnExit;
public TextArea taHome,taAbout, taHelp, taSelectLg;
private InputStream iStream;
private StringBuffer strBuffer;
private Form selectLgForm;
public void startApp() {
Display.init(this);
try {
Resources rs= Resources.open("/restheme.res");
UIManager.getInstance().setThemeProps(rs.getTheme("Theme2"));
} catch (Exception e) {
e.getMessage();
}
displayMainForm();
}
public void displayMainForm()
{
fform = new Form("Football League Standings");
taHome= new TextArea(5,20,TextArea.ANY);
fform.setLayout(new BorderLayout());
fform.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/intro.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taHome.setText(strBuffer.toString());
strBuffer = null;
taHome.setFocusable(false);
taHome.setEditable(false);
taHome.setUIID("Label");
//fform.addComponent(BorderLayout.CENTER,taHome);
btnSelectLeague= (new Button("Select league"));
btnHelp= (new Button("Help"));
btnAbout= (new Button("About"));
btnExit= (new Button("Exit"));
Container mcont = new Container(new BoxLayout(BoxLayout.Y_AXIS));
mcont.addComponent(taHome);
mcont.addComponent(btnSelectLeague);
mcont.addComponent(btnHelp);
mcont.addComponent(btnAbout);
mcont.addComponent(btnExit);
fform.addComponent(BorderLayout.CENTER, mcont);
btnSelectLeague.addActionListener(this);
btnHelp.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
fform.show();
}
/* Command exitCommand = new Command("Exit");
fform.addCommand(exitCommand);
fform.addCommandListener(this);
}
}*/
public void selectLgForm()
{
selectLgForm= new Form("Select League");
taSelectLg= new TextArea(5,20,TextArea.ANY);
selectLgForm.setLayout(new BorderLayout());
selectLgForm.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/selectlg.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taSelectLg.setText(strBuffer.toString());
strBuffer = null;
taSelectLg.setFocusable(false);
taSelectLg.setEditable(false);
taSelectLg.setUIID("Label");
selectLgForm.addComponent(BorderLayout.CENTER,taAbout);
//START OF MENU BUTTONS
selectLgForm.addCommand(new Command("Back")
{
public void actionPerformed(ActionEvent e)
{
displayMainForm();
}
});
selectLgForm.show();
}//END OF MENU BUTTONS
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnSelectLeague){
selectLgForm();
}

my best guesses are:
- selectLgForm.addComponent(BorderLayout.CENTER,taAbout) throws a NullPointerException because taAbout is null.
- or iStream = getClass().getResourceAsStream("/selectlg.txt"); throws a NullPointerException because the text file is not where you think it is.

Related

Problems when closing and reopening a JFrame that uses a SwingWorker to send and receive messages

I am developing a messaging application with sockets. I have an initial JFrame that allows the user to choose a contact to connect to, and lets them choose if they'd like to be the client or the server. When they make this choice, it calls a method in which creates the chat window frame, and also uses a SwingWorker to initialise a connection, create an action listner on the send buton of the chat window so that it sends messages when pressed, and creates a SocketListener that is always listening while the window is open.
This works just fine, however if I close the chat window and then reopen it by choosing server or client again, nothing happens - the frame loads up however I cannot send any messages on it.
I'm not sure what the problem is here, could it be that i'm not disposing of the swing worker or the frame properly? Any help would be greatly appreciated and apologies for my lack of knowledge.
Here is the relevent code for this:
public static void server() {
JButton server = new JButton();
server.setText("Server");
server.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameChoice;
String ip = ipChoice;
String port = portChoice;
try {
server2(port);
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
panel.add(server);
}
public static void server2(String port) throws Exception {
gui.frame();
SwingWorker worker = new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
sockets.serverSetup(port);
gui.sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String msg = gui.newMsg.getText();
gui.newMsg.setText(null);
try {
sockets.sendMsg(msg);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
while(gui.open==true) {
sockets.receiveMsg();
}
sockets.closeConnection();
System.out.println("Closed");
return null;
}
};
worker.execute();
}
network
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
public class network {
static ServerSocket s;
static Socket s1;
static OutputStream s1out;
static DataOutputStream dos;
static InputStream s1in;
static chatWindowScreen gui = new chatWindowScreen();
static String st;
public static Vector sentVec = new Vector();
public static Vector receivedVec = new Vector();
public static Vector messages = new Vector();
public static void serverSetup(String port) throws IOException {
System.out.println("Test");
int portInt = Integer.parseInt(port);
s = new ServerSocket(portInt);
s1 = s.accept();
System.out.println("Server set up");
//sendMsg("Hi");
}
public static void clientSetup(String port, String ip) throws IOException {
System.out.println("Test");
int portInt = Integer.parseInt(port);
s1 = new Socket(ip, portInt);
System.out.println("Client set up");
//receiveMsg();
}
public static void closeConnection() throws IOException {
dos.close();
s1out.close();
s1.close();
}
public static void sendMsg(String message) throws IOException {
System.out.println("Test");
s1out = s1.getOutputStream();
dos = new DataOutputStream(s1out);
dos.writeUTF(message);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String t1 = sdf.format(cal.getTime());
message = t1 + " - " + message;
sentVec.add(message);
receivedVec.add("");
messages.add(message);
gui.sent.setText("Sent \n");
for (int i = 0; i < sentVec.size(); i++) {
gui.sent.append(sentVec.get(i) + "\n");
}
gui.received.setText("Received \n");
for (int i = 0; i < receivedVec.size(); i++) {
gui.received.append(receivedVec.get(i) + "\n");
}
System.out.println("complete");
}
public static void receiveMsg() throws IOException {
System.out.println("Test");
s1in = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1in);
st = (dis.readUTF());
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String t1 = sdf.format(cal.getTime());
st = t1 + " - " + st;
receivedVec.add(st);
sentVec.add("");
messages.add(st);
gui.received.setText("Received \n");
for (int i = 0; i < receivedVec.size(); i++) {
gui.received.append((String) receivedVec.get(i) + "\n");
}
gui.sent.setText("Sent \n");
for (int i = 0; i < sentVec.size(); i++) {
gui.sent.append((String) sentVec.get(i) + "\n");
}
}
public static Vector getSentVec() {
return sentVec;
}
public static Vector getReceivedVec() {
return receivedVec;
}
}
chatWindowScreen
package com.company;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.util.Vector;
public class chatWindowScreen {
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static JTextArea sent;
static JTextArea received;
static JTextArea newMsg;
static JButton sendButton;
public static String msg;
static boolean open = true;
static network sockets = new network();
public static boolean close = false;
public void frame() throws Exception {
System.out.println("GUI opened");
frame.setTitle("Messaging Application");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
System.out.println("Closed");
panel.removeAll();
open=false;
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
sentMsg();
receivedMsg();
msgBox();
sendBtn();
save();
frame.add(panel);
frame.setVisible(true);
}
public static void sentMsg() {
sent = new JTextArea(15, 20);
sent.setText("Sent" + "\n");
sent.setLineWrap(true);
sent.setEditable(false);
JScrollPane pane = new JScrollPane(sent, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane);
}
public static void receivedMsg() {
received = new JTextArea(15, 20);
received.setText("Received" + "\n");
received.setEditable(false);
received.setLineWrap(true);
JScrollPane pane1 = new JScrollPane(received, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane1);
}
public static void msgBox() {
newMsg = new JTextArea(1, 15);
newMsg.setText("");
newMsg.setLineWrap(true);
JScrollPane pane2 = new JScrollPane(newMsg, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(pane2);
}
public static void sendBtn() {
sendButton = new JButton();
sendButton.setText("Send!");
/*sendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
msg = newMsg.getText();
newMsg.setText(null);
SwingWorker worker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
sockets.sendMsg(msg);
return null;
}
};
worker.execute();
try {
sockets.sendMsg(msg);
} catch (IOException e1) {
e1.printStackTrace();
}
msg = null;
}
});*/
panel.add(sendButton);
}
public static void save(){
JButton save = new JButton();
save.setText("Save Conversation");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveToFile save = new saveToFile();
}
});
panel.add(save);
}
}

Understanding command line arguments

Basically I am just writing a socket.
For some reason I keep getting this error though
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.ChatClient.main(ChatClient.java:143)
which is line " String server = args[0]; "
What does the args need to be to fix this issue?
package Main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;
// Class to manage Client chat Box.
public class ChatClient {
Main a = new Main();
/** Chat client access */
static class ChatAccess extends Observable {
private Socket socket;
private OutputStream outputStream;
#Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
socket = new Socket(server, port);
outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() {
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
notifyObservers(line);
} catch (IOException ex) {
notifyObservers(ex);
}
}
};
receivingThread.start();
}
private static final String CRLF = "\r\n"; // newline
/** Send a line of text */
public void send(String text) {
try {
outputStream.write((text + CRLF).getBytes());
outputStream.flush();
} catch (IOException ex) {
notifyObservers(ex);
}
}
/** Close the socket */
public void close() {
try {
socket.close();
} catch (IOException ex) {
notifyObservers(ex);
}
}
}
/** Chat client UI */
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
public ChatFrame(ChatAccess chatAccess) {
this.chatAccess = chatAccess;
chatAccess.addObserver(this);
buildGUI();
}
/** Builds the user interface */
private void buildGUI() {
textArea = new JTextArea(20, 50);
textArea.setEditable(false);
textArea.setLineWrap(true);
add(new JScrollPane(textArea), BorderLayout.CENTER);
Box box = Box.createHorizontalBox();
add(box, BorderLayout.SOUTH);
inputTextField = new JTextField();
sendButton = new JButton("Send");
box.add(inputTextField);
box.add(sendButton);
// Action for the inputTextField and the goButton
ActionListener sendListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = inputTextField.getText();
if (str != null && str.trim().length() > 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText("");
}
};
inputTextField.addActionListener(sendListener);
sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
chatAccess.close();
}
});
}
/** Updates the UI depending on the Object argument */
public void update(Observable o, Object arg) {
final Object finalArg = arg;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(finalArg.toString());
textArea.append("\n");
}
});
}
}
public static void main(String[] args) {
System.out.println("troll");
String server = args[0];
System.out.println("reached here");
int port =2222;
ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access);
frame.setTitle("MyChatApp - connected to " + server + ":" + port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
try {
access.InitSocket(server,port);
} catch (IOException ex) {
System.out.println("Cannot connect to " + server + ":" + port);
ex.printStackTrace();
System.exit(0);
}
}
}
Given:
String server = args[0];
I'd suggest you provide the server name as your first argument to your program
With
public static void main(String[] args)
args is the array of command line args passed in.

SwingWorker and command line process interrupts

I am trying to build a Swing solution for compressing files which is relayed on the rar command line. As the GUI needs to stay responsive I've wrapped the code for dealing with the command line into a SwingWorker class.
SwingWorker<Boolean, String> worker = new SwingWorker<Boolean, String>(){
protected Boolean doInBackground() throws Exception {
Runtime rt = Runtime.getRuntime();
try {
//daj processu da ode u background nekako, da ga ne sjebem sa ctrl + c (winrar umesto rar)
String command = "my command, this works just fine";
Process p = rt.exec(command, null, new File("C:\\Program Files\\WinRar"));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String s = null;
System.out.println("<INPUT>");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("</INPUT>");
InputStream stderr = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
System.out.println("<ERROR>");
String line = null;
while ( (line = br.readLine()) != null){
System.out.println(line);
return false;
}
System.out.println("</ERROR>");
int exitVal = p.waitFor();
//EXIT VALUE IS ALWAYS 0, EVEN IF I INTERRUPT IT WITH CTRL+C
System.out.println("Process exitValue: " + exitVal);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
return false;
}
return true;
}
#Override
protected void process(List<String> chunks) {
// TODO Auto-generated method stub
//SOME GUI UPDATES
}
#Override
protected void done() {
// TODO Auto-generated method stub
Boolean status = false;
try {
status = get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MORE GUI UPDATES
if(status){
tableList.setValueAt("Done", row, 3);
} else{
tableList.setValueAt("Error", row, 3);
}
super.done();
}
};
worker.execute();
When I delete printing of input and error, exit value is printed as soon as rar appears on the screen. So there is no actual point of "waitFor()" method in my code. What I need is to check if rar closed without interrupts (like CTRL + C, or hitting "X" on cmd window) and get the exit code. I've tried adding shutdown hook on runtime (rt variable) but it reacts when I close the whole GUI.
You need to get your input and error streams, and read from them each in its own thread. Right now your error stream never has a chance because of the blocking while loop ahead of it.
I've used the following code (although it is years old...):
Enum: GobblerType.java
enum GobblerType {
ERROR, OUTPUT
}
Class StreamGobbler.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
public class StreamGobbler implements Runnable {
private InputStream is;
private GobblerType type;
private OutputStream os;
public StreamGobbler(InputStream is, GobblerType type) {
this(is, type, null);
}
public StreamGobbler(InputStream is, GobblerType type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}
public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os, true);
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
And then have used it like so:
Process proc = Runtime.getRuntime().exec(.....); // TODO: Fix!
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), GobblerType.ERROR);
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), GobblerType.OUTPUT);
new Thread(errorGobbler).start();
new Thread(outputGobbler).start();
int exitVal = proc.waitFor();
proc.destroy();
OK, I created some code as a proof of concept program. I've modified my Gobbler a bit so that it doesn't require an OutputStream but rather uses a PropertyChangeListener to notify listeners of any text coming from the InputStream. For this to work, all my code is in the same package, and note that package names are key, and you would likely need to change yours. Running this code does behave as expected. It is a bit overly simplistic and probably should use some type of blocking queue for passing information between classes.
GobblerType.java
An enum to distinguish the two type of stream gobblers in use
package pkg2;
public enum GobblerType {
ERROR, OUTPUT
}
StreamGobbler2.java
The stream gobbler that uses an input stream reader to get text from the input stream, puts the text into a text field, and notifies listeners of new text. It uses a PropertyChangeListener for the notification. This is a crude way to producer-consumer, and risks not capturing all passed information. Better would be to use a blocking queue of some sort.
package pkg2;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
public class StreamGobbler2 implements Callable<Void> {
private PropertyChangeSupport support = new PropertyChangeSupport(this);
private InputStream is;
private GobblerType type;
private String text;
public StreamGobbler2(InputStream is, GobblerType type) {
this.is = is;
this.type = type;
}
#Override
public Void call() throws Exception {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
setText(line);
}
return null;
}
public GobblerType getType() {
return type;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}
public void setText(String text) {
String oldValue = null;
String newValue = text;
this.text = text;
support.firePropertyChange(type.toString(), oldValue, newValue);
}
public String getText() {
return text;
}
}
ProcessLauncher.java
This is a non-Swing class that captures the information from the two gobblers. Again, better would be to use blocking queues (next iteration)
package pkg2;
import java.beans.PropertyChangeListener;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ProcessLauncher implements Callable<Integer> {
private ExecutorService execService = Executors.newFixedThreadPool(2);
private List<String> commands;
private List<PropertyChangeListener> listeners = new ArrayList<>();
public ProcessLauncher(List<String> commands) {
this.commands = commands;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.add(listener);
}
#Override
public Integer call() throws Exception {
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
int exitValue = 0;
try (InputStream inputStream = p.getInputStream();
InputStream errorStream = p.getErrorStream()) {
StreamGobbler2 errorGobbler = new StreamGobbler2(inputStream, GobblerType.OUTPUT);
StreamGobbler2 outputGobbler = new StreamGobbler2(errorStream, GobblerType.ERROR);
for (PropertyChangeListener listener : listeners) {
errorGobbler.addPropertyChangeListener(listener);
outputGobbler.addPropertyChangeListener(listener);
}
List<Future<Void>> futures = new ArrayList<>();
futures.add(execService.submit(errorGobbler));
futures.add(execService.submit(outputGobbler));
execService.shutdown();
exitValue = p.waitFor();
for (Future<Void> future : futures) {
future.get();
}
}
return exitValue;
}
}
SwingWorkerWrapper.java
Wrapper to use the above class in a Swing fashion
package pkg2;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.SwingWorker;
public class SwingWorkerWrapper extends SwingWorker<Integer, Void> {
private ProcessLauncher processLauncher;
public SwingWorkerWrapper(List<String> commands) {
processLauncher = new ProcessLauncher(commands);
processLauncher.addPropertyChangeListener(new LauncherListener());
}
#Override
protected Integer doInBackground() throws Exception {
return processLauncher.call();
}
private class LauncherListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
}
}
}
MainGui.java
GUI class that uses the above SwingWorker. Run this class to get the whole show on the road. Once running, press the "Launch Process" button for this program to run the TestProgram in a separate JVM.
package pkg2;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class MainGui extends JPanel {
private static final String[] CMD_TEXT = {"java", "-cp"};
private static final String TEST_PROGRAM = "pkg2.TestProgram";
private JTextArea inputTextArea = new JTextArea(15, 30);
private JTextArea errorTextArea = new JTextArea(15, 30);
private List<String> commands = new ArrayList<>();
public MainGui() {
for (String cmd : CMD_TEXT) {
commands.add(cmd);
}
String classpath = System.getProperty("java.class.path");
commands.add(classpath);
commands.add(TEST_PROGRAM);
inputTextArea.setFocusable(false);
JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
inputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Border outsideBorder = BorderFactory.createTitledBorder("Input Messages");
Border border = BorderFactory.createCompoundBorder(outsideBorder, inputScrollPane.getBorder());
inputScrollPane.setBorder(border);
errorTextArea.setFocusable(false);
JScrollPane errorScrollPane = new JScrollPane(errorTextArea);
errorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outsideBorder = BorderFactory.createTitledBorder("Error Messages");
border = BorderFactory.createCompoundBorder(outsideBorder, errorScrollPane.getBorder());
errorScrollPane.setBorder(border);
JPanel twoAreasPanel = new JPanel(new GridLayout(1, 0, 3, 3));
twoAreasPanel.add(inputScrollPane);
twoAreasPanel.add(errorScrollPane);
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 3, 3));
btnPanel.add(new JButton(new LaunchProcessAction()));
btnPanel.add(new JButton(new ExitAction()));
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(twoAreasPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class SwWrapperListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
SwingWorkerWrapper swW = (SwingWorkerWrapper) evt.getSource();
try {
int exitCode = swW.get();
inputTextArea.append("Exit Code: " + exitCode + "\n");
} catch (InterruptedException e) {
e.printStackTrace();
inputTextArea.append(e.getLocalizedMessage());
inputTextArea.append("\n");
} catch (ExecutionException e) {
e.printStackTrace();
inputTextArea.append(e.getLocalizedMessage());
inputTextArea.append("\n");
}
} else if (GobblerType.OUTPUT.toString().equals(evt.getPropertyName())) {
inputTextArea.append(evt.getNewValue() + "\n");
} else if (GobblerType.ERROR.toString().equals(evt.getPropertyName())) {
errorTextArea.append(evt.getNewValue() + "\n");
}
}
}
private class LaunchProcessAction extends MyAction {
public LaunchProcessAction() {
super("Launch Process", KeyEvent.VK_L);
}
#Override
public void actionPerformed(ActionEvent e) {
SwingWorkerWrapper swWrapper = new SwingWorkerWrapper(commands);
swWrapper.addPropertyChangeListener(new SwWrapperListener());
swWrapper.execute();
}
}
private class ExitAction extends MyAction {
public ExitAction() {
super("Exit", KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private static abstract class MyAction extends AbstractAction {
public MyAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
}
private static void createAndShowGui() {
MainGui mainPanel = new MainGui();
JFrame frame = new JFrame("Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
TestProgram.java
Don't run this program directly, but rather have the Main GUI run this. Be sure that this code and all the code is compiled however
package pkg2;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestProgram extends JPanel {
private JTextField textField = new JTextField(20);
private JSpinner exitCodeSpinner = new JSpinner(new SpinnerNumberModel(0, -10, 10, 1));
public TestProgram() {
SendTextAction sendTextAxn = new SendTextAction();
textField.setAction(sendTextAxn);
JPanel panel1 = new JPanel();
panel1.add(textField);
panel1.add(new JButton(sendTextAxn));
JPanel panel2 = new JPanel();
panel2.add(new JLabel("Exit Code:"));
panel2.add(exitCodeSpinner);
panel2.add(new JButton(new ExitCodeAction()));
panel2.add(new JButton(new ThrowExceptionAction()));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(panel1);
add(panel2);
}
private static abstract class MyAction extends AbstractAction {
public MyAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
}
private class SendTextAction extends MyAction {
public SendTextAction() {
super("Send Text", KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textField.setText("");
System.out.println(text);
}
}
private class ExitCodeAction extends MyAction {
public ExitCodeAction() {
super("Exit Code", KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
int exitCode = (int) exitCodeSpinner.getValue();
System.exit(exitCode);
}
}
private class ThrowExceptionAction extends MyAction {
public ThrowExceptionAction() {
super("Throw Exception", KeyEvent.VK_T);
}
#Override
public void actionPerformed(ActionEvent e) {
// throw some unchecked exception
throw new NumberFormatException("Unchecked exception thrown from within TestProgram");
}
}
private static void createAndShowGui() {
TestProgram mainPanel = new TestProgram();
JFrame frame = new JFrame("Test Program");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

how to access main class jtextfield in Extended class

I have a main class File
and another extend class File 2
how can i access a textfield declared in File with awt and Swing to the extended class File2 ?
main class:-
import java.util.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileReceive extends FileReceiveUtil {
int msgIndex = 1;
Statement s;
public static File f;
public static String phoneNo, phoneNoLo, sk;
public static String str = "";
public static String path = "";
public String ran, ran11;
public String mes, sharedString;
FileReceive() throws Exception {
super("COM4");
}
#Override
public void processSMS(String str) throws Exception {
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("File Receive");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel nameId = new JLabel("Enter Destination Path");
JButton browseb = new JButton("Browse");
JLabel bodyTempId = new JLabel("Path : ");
final JTextField jtf = new JTextField(" ");
JButton sendB = new JButton("Receive");
panel.add(nameId);
panel.add(browseb);
panel.add(bodyTempId);
panel.add(jtf);
panel.add(sendB);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this()
browseb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
String str1 = "";
int m = jf.showOpenDialog(null);
if (m == JFileChooser.APPROVE_OPTION) {
f = jf.getSelectedFile();
str = f.getPath();
path = f.getAbsolutePath();
jtf.setText(path);
}
}
});
sendB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FileReceiveUtil util = null;
try {
util = new FileReceive();
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList al = new ArrayList();
try {
util.startReceive(al, 10);
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Extended class :-
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JTextField;
public abstract class FileReceiveUtil implements Runnable {
private static int responseCode = -1;
private static String userCredentials = null;
private static String cookie = null;
private static String site = null;
private static String actionStr = null;
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private OutputStream outputStream;
private String strPortName;
private InputStream inputStream;
private boolean boolKeepReceiving = true;
private Thread threadRX;
private ArrayList alSMSStore;
private int intDelay;
public FileReceiveUtil(String strPortName) throws Exception {
this.strPortName = strPortName;
initCommPort();
}
private void initCommPort() throws Exception {
boolean boolPortOK = false;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equalsIgnoreCase(strPortName)) {
this.serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(230400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
boolPortOK = true;
break;
}
}
}
if (!boolPortOK) {
throw new Exception("Port " + strPortName + " does not exist!");
}
}
private String readSMS() throws Exception {
StringBuffer sb = new StringBuffer();
sb.append(writeATCmd());
return sb.toString();
}
private String writeATCmd() throws Exception {
//Thread.sleep(2000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[1];
// Thread.sleep(10);
int ch = inputStream.read(data);
//System.out.println(x);
bos.write(data, 0, 1);
byte[] bytes = bos.toByteArray();
File someFile = new File("D:\\yadhu.txt");
FileOutputStream fos = new FileOutputStream(someFile,true);
fos.write(bytes);
fos.flush();
fos.close();
String str = bytes.toString();
System.out.println("Data : "+ str);
return str;
}
private void startReceivingSMS() throws Exception {
final String ERROR = "ERROR";
while (boolKeepReceiving) {
Thread.sleep(intDelay);
try {
System.out.println(" File recieved ");
String str = readSMS();
} catch (Throwable t) {
System.out.println("ERROR RECEIVING MSG");
t.printStackTrace();
}
}
}
final public void startReceive(ArrayList alSMSStore, int intDelay) throws Exception {
this.alSMSStore = alSMSStore;
this.intDelay = intDelay;
threadRX = new Thread(this);
threadRX.start();
}
final public void run() {
try {
startReceivingSMS();
} catch (Throwable t) {
t.printStackTrace();
}
}
final public void stopReceivingSMS() {
this.boolKeepReceiving = false;
}
public ArrayList getReceivedMessages() {
return this.alSMSStore;
}
private static void exit(String errorMsg) {
System.err.println(errorMsg);
System.exit(1);
}
public abstract void processSMS(String message) throws Exception;
}
i want " File someFile = new File("D:\yadhu.txt"); " to change this and add file name from the jtextfield on gui
please help
make the JTextField global in the class instead of a local function item.

Java socket: how the server can reads multiple lines from the client

I create chat app one to one by using Java programming language
I faced issue: client can't send a new message until he receives a message from the server.
You should have a multithreaded application.
The client will run 2 threads:
1) Sender thread which will run on send button. You can every time create a new instance of this thread on clicking send button.
2) The receiver thread will keep on running continuously and check the stream for any message. Once it gets a message on stream it will write the same on console.
Will update you shortly with the code.
Thanks
Written this code long back similarly you can write server using other port
package com.clients;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientFullDuplex extends JFrame implements ActionListener {
private JFrame jframe;
private JPanel jp1, jp2;
private JScrollPane jsp;
private JTextArea jta;
private JTextField jtf;
private JButton send;
private Thread senderthread;
private Thread recieverthread;
private Socket ds;
private boolean sendflag;
public static void main(String[] args) {
try {
ClientFullDuplex sfd = new ClientFullDuplex();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ClientFullDuplex() throws UnknownHostException, IOException {
initGUI();
ds = new Socket("127.0.0.1", 1124);
initNetworking();
}
public void initGUI() {
jframe = new JFrame();
jframe.setTitle("Client");
jframe.setSize(400, 400);
jp1 = new JPanel();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jtf = new JTextField();
send = new JButton("Send");
send.addActionListener(this);
jp1.setLayout(new GridLayout(1, 2, 10, 10));
jp1.add(jtf);
jp1.add(send);
jframe.add(jp1, BorderLayout.SOUTH);
jframe.add(jsp, BorderLayout.CENTER);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta.append("hello client");
}
#Override
public synchronized void addWindowListener(WindowListener arg0) {
// TODO Auto-generated method stub
super.addWindowListener(arg0);
new WindowAdapter() {
#Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
if (ds != null)
try {
ds.close();
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public void initNetworking() {
try {
recieverthread = new Thread(r1);
recieverthread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Runnable r1 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Reciver Thread Started");
recieveMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Sender Thread Started");
sendMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void recieveMessage(Socket rms) throws IOException {
while (true) {
System.out.println(Thread.currentThread().getName()
+ "Reciver Functionality");
BufferedReader br = new BufferedReader(new InputStreamReader(
rms.getInputStream()));
String line = br.readLine();
System.out.println(line);
jta.append("\nServer:"+line);
}
}
public void sendMessage(Socket sms) throws IOException {
System.out.println(Thread.currentThread().getName()
+ "Sender Functionality");
PrintWriter pw = new PrintWriter(sms.getOutputStream(), true);
String sline = jtf.getText();
System.out.println(sline);
pw.println(sline);
jtf.setText("");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == send) {
senderthread = new Thread(r2);
senderthread.start();
}
}
}
This is the code I copied and edited from your earlier post.
The problem is that the input stream from socket is blocking. So my suggestion is to read up on async sockets in java and refactor the code below.
next to that it isn't that difficult to edit posts.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public static void main(String[] args) {
Server chatServer = new Server(5555);
System.out.println("###Start listening...###");
chatServer.startListening();
chatServer.acceptClientRequest();
}
private ServerSocket listeningSocket;
private Socket serviceSocket;
private int TCPListeningPort;
private ArrayList<SocketHanding> connectedSocket;
public Server(int TCPListeningPort)
{
this.TCPListeningPort = TCPListeningPort;
connectedSocket = new ArrayList<SocketHanding>();
}
public void startListening()
{
try
{
listeningSocket = new ServerSocket(TCPListeningPort);
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void acceptClientRequest()
{
try
{
while (true)
{
serviceSocket = listeningSocket.accept();
SocketHanding _socketHandling = new SocketHanding(serviceSocket);
connectedSocket.add(_socketHandling);
Thread t = new Thread(_socketHandling);
t.start();
System.out.println("###Client connected...### " + serviceSocket.getInetAddress().toString() );
}
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class SocketHanding implements Runnable
{
private Socket _connectedSocket;
private PrintWriter socketOut;
private InputStream socketIn;
private boolean threadRunning = true;
private String rmsg;
public SocketHanding(Socket connectedSocket) throws IOException
{
_connectedSocket = connectedSocket;
socketOut = new PrintWriter(_connectedSocket.getOutputStream(), true);
socketIn = _connectedSocket.getInputStream();
}
private void closeConnection() throws IOException
{
threadRunning = false;
socketIn.close();
socketOut.close();
_connectedSocket.close();
}
public void sendMessage(String message)
{
socketOut.println(message);
}
private String receiveMessage() throws IOException
{
String t = "";
if (_connectedSocket.getInputStream().available() > 0)
{
byte[] b = new byte[8192];
StringBuilder builder = new StringBuilder();
int bytesRead = 0;
if ( (bytesRead = _connectedSocket.getInputStream().read(b)) > -1 )
{
builder.append(new String(b, 0, b.length).trim());
}
t = builder.toString();
}
return t;
}
#Override
public void run()
{
while (threadRunning)
{
try
{
rmsg = receiveMessage();
System.out.println(rmsg);
if(rmsg.equalsIgnoreCase("bye"))
{
System.out.println("###...Done###");
closeConnection();
break;
}
else
{
String smsg = "";
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
smsg = keyboard.readLine();
keyboard.close();
sendMessage("Server: "+smsg);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

Categories