Java JNA- Jar application hangs in 32 bit windows system - java

Here's a screenshot application. Compiled with 1.8 JDK, works perfectly well in 64 bit systems, but lags and hangs in two iterations in 32 bit systems.
Basically this application takes a screenshot using robot class, takes the file name from user which is a URL. Truncates and removes all illegal characters from it and saves it using a save as dialog box with time-stamp as the prefix.
I am using Windows Low Level KeyHook to initiate the screenshot with PrtSc key.
Error in 32 bit systems:
It only takes 2 screenshots and then does not respond when I press PrtSc for the 3rd time. Can JFrame cause any problems, it certainly loads up slow. Should I use any alternate text box than JFrame or is it because I have complied in java 1.8 jdk 64 bit environment, which wont work in lower versions of jdk or 32 bit systems.
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
if (info.vkCode == 44) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(0,25,1366,744));
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// prompt the user to enter their name
String name = JOptionPane.showInputDialog(frame, "Enter file name");
// frame.pack();
frame.dispose();
String fileName= dovalidateFile(name);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG", ".png");
fileChooser.setFileFilter(filter);
fileChooser.setSelectedFile(new File (fileName));
int returnVal = fileChooser.showSaveDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
file = validateFile(file);
System.out.println(file);
ImageIO.write(bi, "png", file);
}
}
catch (NullPointerException e1)
{e1.printStackTrace(); }
catch (AWTException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
private File validateFile(File file) {
DateFormat dateFormat = new SimpleDateFormat("HH.mm.ss.ddMMMMMyyyy");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
// System.out.println(dateFormat.format(cal.getTime()));
String filePath = file.getAbsolutePath();
if (filePath.indexOf(".png") == -1) {
filePath += "." + dateFormat.format(cal.getTime()) + ".png";
}
//System.out.println("File Path :" + filePath);
file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private String dovalidateFile(String name) {
String input = name.replace("https://www.","");
input = input.replaceAll("http://www.","");
input = input.replaceAll("https://","");
input = input.replace("http://","");
input = input.replace("/?",".");
input = input.replace("/",".");
input = input.replace("|",".") ;
input = input.replace("%",".");
input = input.replace("<",".");
input = input.replace(">",".");
input = input.replaceAll("\\?",".");
input = input.replaceAll("\\*",".");
input = input.replace(":",".");
input = input.replace("\\",".");
input = Character.toUpperCase(input.charAt(0)) + input.substring(1);
return input;
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
if(!SystemTray.isSupported()){
return ;
}
SystemTray systemTray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(KeyHook.class.getResource("/images/icon.png"));
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
MenuItem close = new MenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "captur", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}

I don't have any experience with JNA, but there are several things that are wrong about your code - I don't think I got them all, but here are some:
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
quit=true;
}
});
The quit=true will never be reached because your program exit()s before it ever goes there.
2.
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
doesn't make any sense since quit will never be true. Also spinning on a variable to detect a change will severly slow down your application (espacially with sleep-times of 10 ms). Why not do the unhook in your ActionListener?
3.
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
Here I'm not too sure because I don't have experience with JNA and the windows event system. The method waits for messages sent to the specified window, but since you don't specify any (second parameter is null) I don't think you will ever get one.
For each callback you are creating a new JFrame but at the end of the method you are only hiding it using frame.setVisible(false);. Since it is still referenced from various Swing-classes it will never be garbage-collected. This creates a memory-leak which will slow down your application. You will have to call frame.dispose() to get rid of it.

Related

Java exe won't display specific jframe but IDE will

I've created a mini quiz game in java and wanted to convert it to an exe..It has photos and sounds attached to it but they are in their respective folders and with the correct paths. When i click on "Insert a new question" the exe works fine, the same thing happens for the "exit" option. But when i click "Play" no window pops up but i don't get an error either..
I tried placing the photos and sounds in the same folder as the class that uses them but it didn't fix the problem. I also tried inserting ".." at the beginning of the URL paths but it didn't fix it either. I've attached the code for the not showing frame.
ArrayList<Question> questions;
int selectedQuestion = 0;
int remainingLife = 3;
Random random = new Random();
int fillAnswer = 0;
String [] answerArray = new String[4];
Clip clipSuccess;
Clip clipFailure;
Clip clipGameOver;
public static Mixer mixer;
public static Clip clip;
javax.swing.Timer timer = new javax.swing.Timer(1000, new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
timer.stop();
jLabel5.setIcon(null);
playRound();
}
});
public PlayGame() {
initComponents();
questions = new ArrayList<Question>();
populateArrayList();
clipSuccess = setSound("../Sounds/success.wav");
clipFailure = setSound("../Sounds/failure.wav");
clipGameOver = setSound("../Sounds/gameOver.wav");
playRound();
}
public void populateArrayList(){
try{
FileInputStream file = new FileInputStream("Questions.dat");
ObjectInputStream inputFile = new ObjectInputStream(file);
boolean endOfFile = false;
while(!endOfFile){
try{
questions.add((Question) inputFile.readObject());
}
catch(EOFException e){
endOfFile = true;
}
catch(Exception f){
JOptionPane.showMessageDialog(null, f.getMessage());
}
}
inputFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public Clip setSound(String soundPath){
Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
/*for(Mixer.Info info: mixInfos){
System.out.println(info.getName() + "----" + info.getDescription());
}*/
mixer = AudioSystem.getMixer(mixInfos[3]);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try {
clip = (Clip)mixer.getLine(dataInfo);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
try{
URL soundURL = PlayGame.class.getResource(soundPath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundURL);
clip.open(audioStream);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
catch(UnsupportedAudioFileException uofe){
uofe.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
return clip;
}
public void successAnswer(){
JOptionPane.showMessageDialog(null, "Απάντησες σωστά!");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon(PlayGame.class.getResource("../Images/Fireworks-animated.gif")));
clipSuccess.setFramePosition(0);
clipSuccess.start();
timer.start();
}
public void wrongAnswer(){
remainingLife--;
JOptionPane.showMessageDialog(null, "Απάντησες λάθος..");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon (PlayGame.class.getResource("../Images/failure.gif")));
if (remainingLife == 0){
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
JOptionPane.showMessageDialog(null, "Δυστυχώς έχασες..");
clipGameOver.setFramePosition(0);
clipGameOver.start();
do{
try{
Thread.sleep(50);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
}while(clipGameOver.isActive());
System.exit(0);
}
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
}
public void playRound(){
selectedQuestion = random.nextInt(questions.size());
jTextField3.setText(Integer.toString(remainingLife));
jTextArea2.setText(questions.get(selectedQuestion).getQuestionName());
for (int i=0; i<4; i++){
fillAnswer = random.nextInt(questions.size());
answerArray[i] = questions.get(fillAnswer).getQuestionAnswer();
if (i==2){
answerArray[i] = questions.get(selectedQuestion).getQuestionAnswer();
continue;
}
}
Collections.shuffle(Arrays.asList(answerArray));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(answerArray));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int selectedAnswer = jComboBox1.getSelectedIndex();
jLabel5.setIcon(null);
if (questions.get(selectedQuestion).getQuestionAnswer().trim().equals(answerArray[selectedAnswer].trim())){
successAnswer();
}
else{
wrongAnswer();
}
timer.start();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
In the IDE the output is a jframe with a question, a combo box of 4 answers, the player's life points and two buttons (one for locking the answer and one for exiting the program). But in the exe form it doesn't even pop up.
EDIT - This is the error the wrapper program shows:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/netbeans/lib/awtextra/AbsoluteLayout
at quiz.PlayGame.initComponents(PlayGame.java:277)
at quiz.PlayGame.(PlayGame.java:62)

Image didn't load in JPanel

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

Why does my java program occasionally not respond saving a file with java filechooser?

I'm using Eclipse saving a .wav file and roughly every fourth or fifth time I run the program it saves the file fine. Most times the program itself just hangs and the screen goes black when the file chooser frame should become visible to choose the location of the file. Does anyone know why this would happen occasionally? Eclipse gives no error in the console window and the code builds fine with no errors.
StopRecording and saveFile are are in the Mainframe class
save method is in another recording setup class
private void stopRecording() {
isRecording = false;
try {
timer.cancel();
RecordButton.setText("Record");
RecordButton.setIcon(iconRecord);
recorder.stop();
saveFile();
} catch (IOException ex) {
JOptionPane.showMessageDialog(Mainframe.this, "Error",
"Error stopping sound recording!",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
private void saveFile() {
JFileChooser fileChooser = new JFileChooser();
FileFilter wavFilter = new FileFilter() {
#Override
public String getDescription() {
return "Sound file (*.WAV)";
}
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
return file.getName().toLowerCase().endsWith(".wav");
}
}
};
fileChooser.setFileFilter(wavFilter);
fileChooser.setAcceptAllFileFilterUsed(false);
int userChoice = fileChooser.showSaveDialog(this);
if (userChoice == JFileChooser.APPROVE_OPTION) {
saveFilePath = fileChooser.getSelectedFile().getAbsolutePath();
if (!saveFilePath.toLowerCase().endsWith(".wav")) {
saveFilePath += ".wav";
}
File wavFile = new File(saveFilePath);
try {
recorder.save(wavFile);
buttonPlay.setEnabled(true);
Keyup.setEnabled(true);
Keydown.setEnabled(true);
btnSave.setEnabled(true);
getKey.setEnabled(true);
System.out.print(saveFilePath);
} catch (IOException ex) {
JOptionPane.showMessageDialog(Mainframe.this, "Error",
"Error saving to sound file!",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public void save(File wavFile) throws IOException {
byte[] audioData = recordBytes.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
AudioInputStream audioInputStream = new AudioInputStream(bais, format,
audioData.length / format.getFrameSize());
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile);
audioInputStream.close();
recordBytes.close();
}
You are calling recorder.save(wavFile); twice. Try calling it just once.

am I overloading my actionListener? JFileChooser

I am attempting to load a saved file from JFileChooser using an actionListener. Here is a snippet of code.
class chooserListener implements ActionListener{
public void actionPerformed (ActionEvent e)
{
if (e.getSource() instanceof JFileChooser){
JFileChooser openFile = (JFileChooser)e.getSource();
String command = e.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)){
File selectedFile = openFile.getSelectedFile();
loadSavedGame(selectedFile);
System.out.print("clicked open file");
tp.setSelectedIndex(0);
}
else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
System.out.print("tester");
tp.setSelectedIndex(0);
}
}
}
}
chooser.addActionListener(new chooserListener());
public void loadSavedGame(File loadfile) {
int allCells = countCells(loadfile);
setMineGame(allCells);
try {
Scanner loadFile = new Scanner(loadfile);
while (loadFile.hasNextInt()){
for (int i = 0; i < allCells; i++){
mineGame.setCell(i, loadFile.nextInt());
//System.out.print("loading saved game");
}
loadFile.close();
mineGame.repaint();
tp.setSelectedIndex(0);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private int countCells(File countCell) {
int cellCount = 0;
try {
Scanner getCells = new Scanner(countCell);
while (getCells.hasNextInt()){
cellCount++;
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(cellCount);
return cellCount;
}
public void setMineGame(int cells) {
game.removeAll();
mineGame.setDifficulty(cells);
mineGame = new Board(statusbar, difficulty);
game.add(mineGame, BorderLayout.CENTER);
game.add(statusbar, BorderLayout.SOUTH);
frame.validate();
frame.repaint();
}
public void setDifficulty(int cells){
if(cells == 256){
difficulty = 0;
}
if (cells == 676){
difficulty = 1;
}
else difficulty = 2;
}
I feel like I have too many methods for the action listener to do. It is hanging when I click 'open', and the test print line 'System.out.print("clicked open file");' does not print. the rest of my code is really large and I'm not sure how to to an SSCE(?). I'm wondering if anyone can see why my actionListener is hanging? thanks IA
It seems like loadSavedGame(File file) takes a lot of time to execute. As this method is running in the Event Dispatch Thread you feel like your program is hanging and never reaches System.out.print("clicked open file"); line. I'd start testing the time of response for this method in a separate test case
Anyway I'd suggest you a few tips:
1) Note there's no need to implement an ActionListener to do your code. You can simple make this:
JFileChooser chooser = new JFileChooser();
int returnValue = chooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION){
//make stuff if approved
} else if(returnValue == JFileChooser.CANCEL_OPTION){
//make stuff if canceled
}
I think it makes people life easier.
2) On the other hand note you have two I/O operations: getting the cells count through countCells(File countCell) method and getting the cells themselves inside loadSavedGame(File loadfile) method. You can do it better reading the file just once:
public List<Integer> getCells(File file){
List<Integer> list = new ArrayList<>();
try {
Scanner getCells = new Scanner(file);
while (getCells.hasNextInt()){
list.add(Integer.valueOf(getCells.nextInt()));
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return list;
}
}
And make this change in loadSavedGame method:
public void loadSavedGame(File loadfile) {
List<Integer> allCells = getCells(loadfile);
setMineGame(allCells.size());
int index = 0;
for(Integer value : allCells){
mineGame.setCell(index, value);
index++;
}
mineGame.repaint();
tp.setSelectedIndex(0);
}

How to save desktop application state?

I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

Categories