Serialization in java, Reinflating the object in an event? - java

I am trying to learn more about java. This program is an attempt to understand events as well as serialization. What i am attempting to do is flatten an object when the user closes the JFrame and re-inflate it when the program is started. I know i can create the serialized file but having it take effect again isn't working. Any help in the right direction would be wonderful. Thank you in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
import java.io.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class tempusFugit extends JFrame implements ActionListener, Serializable, WindowListener
{
String fileN = "tf.txt";
public int ToL = 0;
String outT = Integer.toString(ToL);
JLabel jl = new JLabel(outT);
FileOutputStream fos = null;
ObjectOutputStream out = null;
public tempusFugit()
{
Timer timer = new Timer(1000, this);
setBounds(250, 250, 250, 190);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT) );
setVisible(true);
add(jl);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
++ToL;
outT = Integer.toString(ToL);
jl.setText(outT);
validate();
repaint();
}
public static void main(String[] args)
{
tempusFugit tf = new tempusFugit();
tf.addWindowListener( tf );
}
public void windowDeactivated(WindowEvent e)
{
}
public void windowActivated(WindowEvent e)
{
}
public void windowDeiconified(WindowEvent e)
{
}
public void windowIconified(WindowEvent e)
{
}
public void windowClosed(WindowEvent e)
{
}
public void windowClosing(WindowEvent e)
{
try
{
fos = new FileOutputStream(fileN);
out = new ObjectOutputStream(fos);
out.writeObject(this);
out.close();
}
catch(IOException ex)
{
}
}
public void windowOpened(WindowEvent e)
{
try
{
tempusFugit tf = new tempusFugit();
FileInputStream fis = new FileInputStream(fileN);
ObjectInputStream in = new ObjectInputStream(fis);
tf = (tempusFugit)in.readObject();
this.ToL = tf.ToL;
}
catch(IOException ex)
{
}
catch(ClassNotFoundException ce)
{
}
}
}
I assume i'm trying to recreate the object at the wrong time. Even though the object is serialized correctly i can not access it again with the windowOpened function. Do i need to try to use
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
somehow?
What i end up with is an error saying i am trying to access a Final object (i assume my this). I find that very odd that i cant repopulate my current 'this' with another similar object.
Am i way off base?
Again thank you for your time.

Note that there are much simpler ways to do this than serializing the frame, and much better things to serialize than the frame itself.
See What is the best practice for setting JFrame locations in Java? for an example of storing the location and size of a frame. It would be trivial to adapt that to store the count.
But here is an attempt based on your code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
import java.io.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class tempusFugit extends JFrame implements ActionListener, Serializable, WindowListener
{
String fileN = "tf.txt";
public int ToL = 0;
JLabel jl = new JLabel("" + ToL);
public tempusFugit()
{
Timer timer = new Timer(1000, this);
setBounds(250, 250, 250, 190);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT) );
setVisible(true);
add(jl);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
++ToL;
jl.setText("" + ToL);
validate();
repaint();
}
public static void main(String[] args)
{
tempusFugit tf = new tempusFugit();
tf.addWindowListener( tf );
}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e)
{
try
{
FileOutputStream fos = new FileOutputStream(fileN);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(this);
out.flush();
out.close();
setVisible(false);
System.exit(0);
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null, ex);
System.exit(1);
}
}
public void windowOpened(WindowEvent e)
{
try
{
tempusFugit tf;// = new tempusFugit();
FileInputStream fis = new FileInputStream(fileN);
ObjectInputStream in = new ObjectInputStream(fis);
tf = (tempusFugit)in.readObject();
this.ToL = tf.ToL;
//tf.setVisible(false);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ce)
{
ce.printStackTrace();
}
}
}

Related

NotFoundException even when a barcode is in the picture

I am trying to make a simple barcode scanner project for fun. And I've run into a slight problem. I am using zXing and Webcam Capture for this.
Even if a Barcode is present in the picture, Java keeps telling me none is found through the NotFoundException. I look for a frame every time webcamImageObtained is run (which I assume is every frame?) and then I look for a barcode in the frame that I captured.
I took this picture with that webcam (Ironically using the code hah):
When I hover over this barcode it reports about 30 images per second and otherwise about 7-8 when it looks at me from my screen (if that means anything).
Whenever I find a code, I want to add it to a JList (not accounting for duplicates and the likes yet).
I call this code every time webcamImageObtained(WebcamEvent we) fires:
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the entire class:
package sandbox_webcam;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamDiscoveryEvent;
import com.github.sarxos.webcam.WebcamDiscoveryListener;
import com.github.sarxos.webcam.WebcamEvent;
import com.github.sarxos.webcam.WebcamListener;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamPicker;
import com.github.sarxos.webcam.WebcamResolution;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class AdvancedWebcamPanelExample extends JFrame implements Runnable, WebcamListener, WindowListener, UncaughtExceptionHandler, ItemListener, WebcamDiscoveryListener {
private Webcam webcam = null;
private WebcamPanel panel = null;
private WebcamPicker picker = null;
private JButton button = null;
private JList list = null;
private ActionListener buttonListener = null;
private com.google.zxing.Reader reader = new com.google.zxing.MultiFormatReader();
#Override
public void run() {
Webcam.addDiscoveryListener(this);
setTitle("Java Webcam Capture POC");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addWindowListener(this);
picker = new WebcamPicker();
picker.addItemListener(this);
webcam = picker.getSelectedWebcam();
if (webcam == null) {
System.out.println("No webcams found...");
System.exit(1);
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(AdvancedWebcamPanelExample.this);
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
buttonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (webcam != null) {
BufferedImage image = webcam.getImage();
JFileChooser filechooser = new JFileChooser();
int saveValue = filechooser.showDialog(button, "Save");
if (saveValue == JFileChooser.APPROVE_OPTION) {
try {
File f = filechooser.getSelectedFile();
ImageIO.write(image, "png", new File(f.getAbsolutePath() + ".png"));
System.out.println("Picture saved at: " + f.getAbsolutePath());
} catch (IOException ex) {
System.err.println("Failed to save the picture!");
ex.printStackTrace();
}
}
} else {
System.err.println("no webcam found to take a picture");
}
}
};
button = new JButton("Snap a Picture!");
button.addActionListener(buttonListener);
list = new JList();
list.setMinimumSize(new Dimension(200,this.getHeight()));
add(picker, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
add(list, BorderLayout.EAST);
pack();
setVisible(true);
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-starter");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
#Override
public void webcamOpen(WebcamEvent we) {
System.out.println("webcam open");
}
#Override
public void webcamClosed(WebcamEvent we) {
System.out.println("webcam closed");
}
#Override
public void webcamDisposed(WebcamEvent we) {
System.out.println("webcam disposed");
}
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void windowOpened(WindowEvent e) {
// do nothing
}
#Override
public void windowClosing(WindowEvent e) {
// do nothing
}
#Override
public void windowClosed(WindowEvent e) {
webcam.close();
}
#Override
public void windowIconified(WindowEvent e) {
System.out.println("webcam viewer paused");
panel.pause();
}
#Override
public void windowDeiconified(WindowEvent e) {
System.out.println("webcam viewer resumed");
panel.resume();
}
#Override
public void windowActivated(WindowEvent e) {
// do nothing
}
#Override
public void windowDeactivated(WindowEvent e) {
// do nothing
}
#Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println(String.format("Exception in thread #s", t.getName()));
e.printStackTrace();
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem() != webcam) {
if (webcam != null) {
panel.stop();
remove(panel);
webcam.removeWebcamListener(this);
webcam.close();
webcam = (Webcam) e.getItem();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(this);
System.out.println("selected " + webcam.getName());
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
add(panel, BorderLayout.CENTER);
pack();
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-stopper");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
}
}
#Override
public void webcamFound(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.addItem(event.getWebcam());
}
}
#Override
public void webcamGone(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.removeItem(event.getWebcam());
}
}
}
Am I missing something about how this library scans for a barcode?
EDIT
Not sure this helps much..
Mar 02, 2015 10:04:34 PM sandbox_webcam.AdvancedWebcamPanelExample webcamImageObtained
SEVERE: null
com.google.zxing.NotFoundException
Throws exception here:
Result result = reader.decode(bitmap);
There is a different question which has some available answers: Android zxing NotFoundException
As James said, it is a good idea to try with bar codes on different media (paper/screen) if it is not working, and in different circumstances and lighting conditions. Particularly ensure that you have enough light, and that the FPS of the camera is high enough while it is pointed at the barcode.
For debugging, one could also convert the BinaryImage back into a viewable format and check whether the barcode is actually visible after conversion to black-and-white.

issue in sending the socket output to GUI

I wrote this simple multi threaded chatroom, and I am trying to send the client/server output to GUI to display it in chatroom text area but I get null pointer exception at the following line:
output.write(line + "\n");
here is the full code for GUI:
import java.awt.*;
import javax.swing.*;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JButton;
import java.io.Writer;
public class GUI {
private JFrame frame;
private JButton btnSend, btnConnect;
private JTextArea txtChat;
private JTextField fldText, fldName;
private JList clientList;
private DefaultListModel listModel;
private JScrollPane sc, scClients;
private JPanel jpS2All, jpS2Client, jpS2Text;
private String Name;
private JLabel lblErr;
private Writer output;
public GUI(String Name, Writer output) {
this.Name = Name;
this.output = output;
}
public GUI() {
}
class handler implements ActionListener, MouseListener {
handler(String Name) {
}
handler() {
}
#Override
public void actionPerformed(ActionEvent e) {
clients(); //it seems this line made the error because it creates the
listModel.addElement(Name);//gui and sends the output to textSend actionlistener
//to display it in gui
//while the output is empty, right?
//is there any way to handle this?
}
#Override
public void mouseClicked(MouseEvent e) {
fldName.setText("");
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
} //end of handler
class textSend implements ActionListener {
textSend(String Name, Writer output) {
}
#Override
public void actionPerformed(ActionEvent e) {
String line = fldText.getText();
try {
output.write(line + "\n"); // the null exception error shows the
output.flush(); // error source at this line!
} catch (IOException ioe) {
txtChat.append("Other party hung up!");
}
String contenet = Name + ":" + output;
txtChat.append(contenet);
fldText.setText("");
}
}//end of textSend
public void creatServer() {
frame = new JFrame("enter");
frame.setBounds(50, 50, 300, 200);
btnConnect = new JButton("connect");
lblErr = new JLabel();
lblErr.setText("");
frame.add(btnConnect, BorderLayout.EAST);
fldName = new JTextField();
fldName.setText("enter your name");
fldName.addMouseListener(new handler());
btnConnect.addActionListener(new handler(getName()));
frame.add(fldName, BorderLayout.CENTER);
frame.setVisible(true);
}
public void clients() { //to create the chatroom GUI
frame = new JFrame("friends");
frame.setBounds(100, 100, 400, 400);
jpS2All = new JPanel();
txtChat = new JTextArea();
txtChat.setRows(25);
txtChat.setColumns(25);
txtChat.setEditable(false);
sc = new JScrollPane(txtChat);
jpS2All.add(sc);
frame.add(jpS2All, BorderLayout.WEST);
jpS2Text = new JPanel();
////////////////////////
fldText = new JTextField();
fldText.setColumns(34);
fldText.setHorizontalAlignment(JTextField.RIGHT);
fldText.addActionListener(new textSend(getName(), output));
jpS2Text.add(fldText);
frame.add(jpS2Text, BorderLayout.SOUTH);
/////////
jpS2Client = new JPanel();
listModel = new DefaultListModel();
clientList = new JList(listModel);
clientList.setFixedCellHeight(14);
clientList.setFixedCellWidth(100);
scClients = new JScrollPane(clientList);
frame.add(jpS2Client.add(scClients), BorderLayout.EAST);
/////////
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}//end of clients
public String getName() {
Name = fldName.getText();
return Name;
}
public void appendText(final String message) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
txtChat.append(message);
}
});
}
}
server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class server {
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
while (true) {
Socket socket = serverSocket.accept();
ClientThread t = new ClientThread(socket);
t.start();
}
}
public static void main(String[] args) throws IOException {
server server = new server();
server.start();
}
class ClientThread extends Thread {
Socket socket;
InputStream sInput;
OutputStream sOutput;
GUI gui = new GUI();
String Name;
ClientThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader sInput
= new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer sOutput = new OutputStreamWriter(socket.getOutputStream());
Name = gui.getName();
gui = new GUI(Name, sOutput);
try {
String line;
while ((line = sInput.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException e) {
}
}
}
}
client side:
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class client {
private Socket s;
private String Name;
private GUI gui;
private Writer output;
private BufferedReader input;
public void start() {
try {
s = new Socket("127.0.0.1", 1234);
} catch (IOException ex) {
}
try {
input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output = new OutputStreamWriter(s.getOutputStream());
} catch (IOException eIO) {
}
Name = gui.getName();
new GUI(Name, output);
new ListenFromServer().start();
}
public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}
class ListenFromServer extends Thread {
public void run() {
try {
String line;
while ((line = input.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I know my question is a bit cumbersome but I really appreciate to help me handle this issue!
I am looking at your code and it is obvious that output is null when you attempt output.write(line + "\n"); Therefore I went and looked for the possible path of execution that could leave output un-initialized. This is where debugging comes in very handy.
Here is your execution path:
In your main method of client you create a new GUI and then call gui.creatServer();
public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}
output has not been assigned and is still null
in the creatServer(); method you have this line:
fldName.addMouseListener(new handler());
which the actionPerformed method of handler calls the clients(); method which has the line:
fldText.addActionListener(new textSend(getName(), output));
note output is still null
(now your textSend class doesn't even do anything inside the constructor but that aside even if it did you are still using the output variable from the GUI class)
you have the actionPerformed method in the textSend class that has the line:
output.write(line + "\n");
Without ever initializing output it is still null, which gives you the NullPointer
Please see What is a NullPointerException, and how do I fix it? as #markspace linked in the comments. In addition you should really learn how to debug small programs.
See the following links:
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
http://blogs.msdn.com/b/smallbasic/archive/2012/10/09/how-to-debug-small-basic-programs.aspx
Again in addition, consider using Anonymous classes to ease up on those lines of code, which also makes the code easier to debug and more readable.
One last thought, remember to use standard Naming Conventions for the language you are using. your code currently has a lot of incorrect lowercase classes and some uppercase methods/properties.
the error message shows that one of the variable used in the expression was null. This may be either output or line.
As chancea already mentioned, you are calling the GUI() constructor with no arguments, so the output field is not initialized. You should remove the constructor with no arguments when you have no way to initialize the output field in it and only leave the one with arguments.

Unable to load a saved JButton

I'm making a program that is saving an array of JButtons to a file .btn. here is the code that is being saved:
package avtech.software.compunav;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.swing.JButton;
public class Buttons implements Serializable {
public static Button[] buttons = new Button[15];
public Buttons() {
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new Button();
buttons[i].setText("Unassigned");
}
}
public JButton[] getButtons() {
return buttons;
}
public JButton getButton(int index) {
return buttons[index];
}
public void setButtonText(String txt, int index) {
buttons[index].setText(txt);
}
public void setButtonAction(String action, int index) {
}
public void save() {
try {
File dir = new File(Core.baseDir + "/bin/buttons.btn");
FileOutputStream fos = new FileOutputStream(dir);
ObjectOutputStream oos = new ObjectOutputStream(fos);
if (dir.exists())
dir.delete();
oos.writeObject(this);
oos.flush();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Button is a class that extends JButton, and here is that code:
package avtech.software.compunav;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import CompuNav.main.Dialogs;
public class Button extends JButton implements ActionListener {
private String action = "";
public Button() {
addActionListener(this);
}
public void setAction(String s) {
action = s;
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (action.equals(""))
return;
File file = new File(action);
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException e1) {
Dialogs.msg("Could not open " + action);
}
}
}
Basically, the code is saving. there is a file called buttons.btn in the correct directory. The problem is, when I use the load method here:
try {
FileInputStream fis = new FileInputStream(baseDir
+ "/bin/buttons.btn");
ObjectInputStream ois = new ObjectInputStream(fis);
buttonsClass = (Buttons) ois.readObject();
ois.close();
} catch (Exception e) {}
after making a new object of the Buttons and saving it, I get a nullPointerException when trying to call buttonsClass.getButton(0);, implying that the JButtons are not saved when i save the class.
Any reason as to why, and any idea how to fix this?
public static Button[] buttons = new Button[15];
This variable should not be static if you want it to be serialized.

Processing backspace in Java Swing

I have Java Swing code that process user's input as follows:
public class UserEntryPane extends JPanel implements DocumentListener {
…
#Override
public void insertUpdate(DocumentEvent e) {
try {
String c = a.getText(...);
if (c.equals("\n")) {
System.out.println(...);
...
}
else {
...
}
} catch (Exception e) {
e.printStackTrace();
}
}
The issue is that this method is not invoked when Backspace is pressed. How can I detect user's Backspace to process it correctly?
Seems you use DocumentListener.
Look at method removeUpdate. It called, when you use backspace.
#Override
public void removeUpdate(DocumentEvent arg0) {
}
import java.awt.FlowLayout;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class UseBackSPace extends JFrame
{
Robot r;
void start()
{
try
{
JFrame f = new JFrame("UseBackSPace");
JTextField txt = new JTextField(20);
f.add(txt);
f.setSize(500, 200);
f.setVisible(true);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
// f.setLocation(400, 400);
r = new Robot();
r.setAutoDelay(900);
r.keyPress(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_H);
r.keyPress(KeyEvent.VK_I);
r.keyPress(KeyEvent.VK_S);
r.keyPress(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_I);
r.keyPress(KeyEvent.VK_S);
r.keyPress(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_F);
r.keyPress(KeyEvent.VK_U);
r.keyPress(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_BACK_SPACE);
} catch (Exception e)
{
}
}
public static void main(String args[])
{
new UseBackSPace().start();
}
}

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories