"Open file..." dialog box won't close - java

Hi, I am new to the Java language. I used Eclipse as my development tool. I have code to open the file dialog box and it did, but I have two problems:
When I select the file and click the "Open" button in the dialog box, the dialog box appears again instead of closing.
Sometimes the text in filename textbox in the dialog is unclear and/or the text on the button disappears. If I enlarge the dialog, the text will show completely.
Here is my code:
package PDFAnnotationPackage;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.io.*;
public class MainForm extends JFrame implements ActionListener {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MainForm();
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(300, 300);
setLocation(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(MainForm.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println("Open menu item clicked");
// load from file
}
if (fileChooser.showOpenDialog(this) == JFileChooser.CANCEL_OPTION ) {
}
} else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
}
How can I solve the issues? Thanks in advance.

Your dialog box appear again because you're calling a method showOpenDialog twice. Try this
if (command.equals("Quit")) {
// Close application
} else if (command.equals("Open")) {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(parent);
if (returnVal == FileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
} else if (command.equals("Save")) {
// Save menu item action
}

You're calling fileChooser.showOpenDialog(this) multiple times and that's why your program is behaving as it's behaving. Instead call fileChooser.showOpenDialog(this) once, and save its value to a variable.
In fact, you don't even need this empty block:
if (fileChooser.showOpenDialog(this) ==
JFileChooser.CANCEL_OPTION ) {
}
So get rid of it!

Related

The text in dialog box is missing

Hi I have a java program. I use Eclipse as my tool. Also I have installed Java 7 Update 51, Java SE Development Kit 7 Update 51. My code to open the dialog box for selecting the file. It works, but the problem is the text on button or textbox on dialog box is missing sometime.
Would some one tell me how to solve this issue. Thanks in advance
There is my code:
package MyPackage;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.io.*;
public class MainForm extends JFrame implements ActionListener {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MainForm();
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
//setSize(600, 300);
//setLocation(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
}
A problem in your code is in which thread is being executed. Most Swing methods can only be executed in a very specific thread called Event Dispatch Thread. Because you are not doing this correctly your application will tend to have inconsistent errors. The larger it gets the easier it is that something goes wrong.
To properly execute in the EDT you need to change your main method to:
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
invokeLater schedules the execution of the MainForm constructor to the EDT, so that the GUI initialization code is executed in the proper thread.
I don't know if this alone will solve the problem but will surely solve future non-reproducible missbehaviours. I've personally seen some threading problems other times with JFileChooser, there are or have been several reported bugs with the thread management of this class.
Note that this is a core rule of Swing that even the Hello world complies.

Cannot hide SystemTray JPopupMenu when it loses focus

This question is similar to this one. What I have is a JPopupMenu that pops up from an icon on the system tray. At this point, the system tray is the only manifestation of the program. That is, there are no other windows open, the icon in the system tray is the only way I can access the program. I used a JPopupMenu over the AWT PopupMenu because I wanted to get the system Look and Feel applied to the popup menu - when I used just a plain PopupMenu, I could not get the system's Look and Feel, I just kept getting Swing's Metal Look and Feel. I used this work-around to get this behavior (described here):
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
systemTrayPopupMenu.setInvoker(systemTrayPopupMenu);
systemTrayPopupMenu.setVisible(true);
}
}
};
When I right click on the tray icon, it shows the menu, and naturally, when I make a selection, the menu disappears. However, when I bring up the menu, then click out of it, it does not disappear. To make it disappear currently, I have to either make a selection, or select one of the menu items that are disabled.
I tried adding a FocusListener to it, however, there is no indication that the focusLost or focusGained methods ever get called. Additionally, I cannot make it disappear when another Window gains focus because there are no other windows present. Since this pop-up menu comes from a TrayIcon and not a typical button, I cannot use the solution mentioned here to get around the FocusListener not calling focusLost.
Ultimately, what I am wondering is either:
1) Is there a way to get the system's look and feel for a normal AWT PopupMenu?, or
2) Is there a way to make the JPopupMenu disappear when it loses focus?
EDIT: Per request, here is my SSCCE:
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingSystemTray {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new SwingSystemTray ();
} catch (Exception e) {
System.out.println("Not using the System UI defeats the purpose...");
e.printStackTrace();
}
}
});
}
protected SystemTray systemTray;
protected TrayIcon trayIcon;
protected JPopupMenu systemTrayPopupMenu;
protected Image iconImage;
public SwingSystemTray () throws IOException {
iconImage = getIcon ();
if (SystemTray.isSupported()) {
systemTray = SystemTray.getSystemTray();
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
systemTrayPopupMenu.setInvoker(systemTrayPopupMenu);
systemTrayPopupMenu.setVisible(true);
}
}
});
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
System.out.println("Could not place item at tray. Exiting.");
}
}
}
protected JPopupMenu buildSystemTrayJPopupMenu () {
final JPopupMenu menu = new JPopupMenu ();
final JMenuItem showMenuItem = new JMenuItem("Show");
final JMenuItem hideMenuItem = new JMenuItem("Hide");
final JMenuItem exitMenuItem = new JMenuItem("Exit");
hideMenuItem.setEnabled(false);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent ae) {
Object source = ae.getSource();
if (source == showMenuItem) {
System.out.println("Shown");
showMenuItem.setEnabled(false);
hideMenuItem.setEnabled(true);
}
else if (source == hideMenuItem) {
System.out.println("Hidden");
hideMenuItem.setEnabled(false);
showMenuItem.setEnabled(true);
}
else if (source == exitMenuItem) {
System.exit(0);
}
}
};
for (JMenuItem item : new JMenuItem [] {showMenuItem, hideMenuItem, exitMenuItem}) {
if (item == exitMenuItem) menu.addSeparator();
menu.add(item);
item.addActionListener(listener);
}
return menu;
}
protected Image getIcon () throws IOException {
// Build the 16x16 image programmatically, start with BMP Header
byte [] iconData = new byte[822];
System.arraycopy(new byte [] {0x42,0x4d,0x36,0x03, 0,0,0,0, 0,0,0x36,0,
0,0,0x28,0, 0,0,16,0, 0,0,16,0, 0,0,16,0, 24,0,0,0, 0,0,0,3},
0, iconData, 0, 36);
for (int i = 36; i < 822; iconData[i++] = 0);
for (int i = 56; i < 822; i += 3) iconData[i] = -1;
return ImageIO.read(new java.io.ByteArrayInputStream(iconData));
}
}
I found a hack that I feel will work just nicely. I have yet to test it in Windows XP, but it works in Windows 7. This involves adding a "hidden dialog" that displays behind the popup menu, as if the popup menu originated from the hidden dialog in the first place. The only real trick is getting the hidden dialog to stay behind the popup menu. At least in Windows 7, it displays behind the system tray, so you never really see it in the first place. A WindowFocusListener can be added to this hidden dialog, and so when you click out of the popup menu, you are also clicking out of the hidden dialog. I have added this capability to the SSCCE that I posted previously to illustrate how adding this works:
package org.test;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingSystemTray {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
try {
/* We are going for the Windows Look and Feel here */
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new SwingSystemTray ();
} catch (Exception e) {
System.out.println("Not using the System UI defeats the purpose...");
e.printStackTrace();
}
}
});
}
protected SystemTray systemTray;
protected TrayIcon trayIcon;
protected JPopupMenu systemTrayPopupMenu;
protected Image iconImage;
/* Added a "hidden dialog" */
protected JDialog hiddenDialog;
public SwingSystemTray () throws IOException {
iconImage = getIcon ();
if (SystemTray.isSupported()) {
systemTray = SystemTray.getSystemTray();
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
/* Place the hidden dialog at the same location */
hiddenDialog.setLocation(me.getX(), me.getY());
/* Now the popup menu's invoker is the hidden dialog */
systemTrayPopupMenu.setInvoker(hiddenDialog);
hiddenDialog.setVisible(true);
systemTrayPopupMenu.setVisible(true);
}
}
});
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent ae) {
System.out.println("actionPerformed");
}
});
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
System.out.println("Could not place item at tray. Exiting.");
}
}
/* Initialize the hidden dialog as a headless, titleless dialog window */
hiddenDialog = new JDialog ();
hiddenDialog.setSize(10, 10);
/* Add the window focus listener to the hidden dialog */
hiddenDialog.addWindowFocusListener(new WindowFocusListener () {
#Override
public void windowLostFocus (WindowEvent we ) {
hiddenDialog.setVisible(false);
}
#Override
public void windowGainedFocus (WindowEvent we) {}
});
}
protected JPopupMenu buildSystemTrayJPopupMenu () {
final JPopupMenu menu = new JPopupMenu ();
final JMenuItem showMenuItem = new JMenuItem("Show");
final JMenuItem hideMenuItem = new JMenuItem("Hide");
final JMenuItem exitMenuItem = new JMenuItem("Exit");
hideMenuItem.setEnabled(false);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent ae) {
/* We want to make sure the hidden dialog goes away after selection */
hiddenDialog.setVisible(false);
Object source = ae.getSource();
if (source == showMenuItem) {
System.out.println("Shown");
showMenuItem.setEnabled(false);
hideMenuItem.setEnabled(true);
}
else if (source == hideMenuItem) {
System.out.println("Hidden");
hideMenuItem.setEnabled(false);
showMenuItem.setEnabled(true);
}
else if (source == exitMenuItem) {
System.exit(0);
}
}
};
for (JMenuItem item : new JMenuItem [] {showMenuItem, hideMenuItem, exitMenuItem}) {
if (item == exitMenuItem) menu.addSeparator();
menu.add(item);
item.addActionListener(listener);
}
return menu;
}
protected Image getIcon () throws IOException {
// Build the 16x16 image programmatically, start with BMP Header
byte [] iconData = new byte[822];
System.arraycopy(new byte [] {0x42,0x4d,0x36,0x03, 0,0,0,0, 0,0,0x36,0,
0,0,0x28,0, 0,0,16,0, 0,0,16,0, 0,0,16,0, 24,0,0,0, 0,0,0,3},
0, iconData, 0, 36);
for (int i = 36; i < 822; iconData[i++] = 0);
for (int i = 56; i < 822; i += 3) iconData[i] = -1;
return ImageIO.read(new java.io.ByteArrayInputStream(iconData));
}
}
This solution gives me requirement #2 that I was looking for, which is to make the JPopupMenu disappear when it loses focus on a system tray using the Windows system look and feel.
Note: I have not gotten the JPopupMenu feature to work on the system tray in CentOS/RedHat Linux. For those, I will have to just use a normal AWT PopupMenu.
A JPopupMenu can't be displayed by itself. That is it needs to be added to a window. Try to use a WindowListener and then hide the popup on a windowDeactivated() event. After the popup is visible you should be able to get the window by using:
Window window = SwingUtilities.windowForComonent(systemTrayPopupMenu);
I just used a MouseListener on the JPopup menu which invokes a timer Thread upon mouse exit; if the mouse re-enters, I reset the "mouseStillOnMenu" flag. Set the "Thread.sleep() value to however long you want the user to be able leave the menu - if you click on a a menu item normally, the default menu close behavior is invoked and closes the menu.
#Override
public void mouseEntered(MouseEvent arg0) {
mouseStillOnMenu = true;
}
#Override
public void mouseExited(MouseEvent arg0) {
mouseStillOnMenu = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000); //waits one second before checking if mouse is still on the menu
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!isMouseStillOnMenu()) {
jpopup.setVisible(false);
}
}
}).start();
}

How to delete a file through JFileChooser?

How could i delete a file in JFileChooser? I know that the AWT since being written in native could has an option to delete a file from it using the simple Delete button.
But what if i would like to delete the file in JFileChooser? When i am trying to delete, it i got an exception that the File is being accessed by another program and hence could not be deleted.
Two questions that i would like to ask in this situation are..
Questions
Is there any hack to delete a file through JFileChooser?
Why i am not getting File is being accessed by another program when i am deleting in FileDialog. Is it because it is written in native code?
Any help is appreciated. Thanks in advance.
Yeah! I got it! I even updated the JFileChooser after the file was deleted.
Updated
Added functionality to delete multiple files and modified jf.getUI().rescanCurrentDirectory(jf) to jf.rescanCurrentDirectory() and removed superfluous PropertyChangeListener as per sir Rob Camick's suggestion.
/*
* #see http://stackoverflow.com/a/17622050/2534090
* #author Gowtham Gutha
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
class DeleteThroughJFileChooser extends JFrame
{
JButton jb;
JFileChooser jf;
File[] selectedFiles;
public DeleteThroughJFileChooser()
{
// Create and show GUI
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Delete through JFileChooser");
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create JFileChooser
jf=new JFileChooser();
// Allow multiple selection
jf.setMultiSelectionEnabled(true);
// Create JButton
jb=new JButton("Open JFileChooser");
// Add ActionListener to it
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// Show the file chooser
showFileChooser();
}
});
// Register the delete action
registerDelAction();
// Add JButton jb to JFrame
add(jb);
}
private void showFileChooser()
{
// Show the open dialog
int op=jf.showOpenDialog(this);
}
private void registerDelAction()
{
// Create AbstractAction
// It is an implementation of javax.swing.Action
AbstractAction a=new AbstractAction(){
// Write the handler
public void actionPerformed(ActionEvent ae)
{
JFileChooser jf=(JFileChooser)ae.getSource();
try
{
// Get the selected files
selectedFiles=jf.getSelectedFiles();
// If some file is selected
if(selectedFiles!=null)
{
// If user confirms to delete
if(askConfirm()==JOptionPane.YES_OPTION)
{
// Call Files.delete(), if any problem occurs
// the exception can be printed, it can be
// analysed
for(File f:selectedFiles)
java.nio.file.Files.delete(f.toPath());
// Rescan the directory after deletion
jf.rescanCurrentDirectory();
}
}
}catch(Exception e){
System.out.println(e);
}
}
};
// Get action map and map, "delAction" with a
jf.getActionMap().put("delAction",a);
// Get input map when jf is in focused window and put a keystroke DELETE
// associate the key stroke (DELETE) (here) with "delAction"
jf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"),"delAction");
}
public int askConfirm()
{
// Ask the user whether he/she wants to confirm deleting
// Return the option chosen by the user either YES/NO
return JOptionPane.showConfirmDialog(this,"Are you sure want to delete this file?","Confirm",JOptionPane.YES_NO_OPTION);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new DeleteThroughJFileChooser();
}
});
}
}
Why would you delete a file from the chooser?
Use the jfilechooser to get the name of the file and location store as a variable. Close the file jfilechooser. Then delete the file.
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Also, I found this code that might prove to be usefull if you want the functionality to be in the jfilechooser itself. From Here. To run this you will also need This. Swing file
import darrylbu.util.SwingUtils;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
public class FileChooserDeleteMenu {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FileChooserDeleteMenu().makeUI();
}
});
}
public void makeUI() {
final JFileChooser chooser = new JFileChooser();
final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
JPopupMenu popup = list.getComponentPopupMenu();
JMenuItem item = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser.getSelectedFile() != null) {
JOptionPane.showConfirmDialog(chooser,
"Delete " + chooser.getSelectedFile().getAbsolutePath() + "?",
"Confirm delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
}
}
});
popup.add(item);
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if (e.getSource() == list) {
list.setSelectedIndex(list.locationToIndex(p));
} else {
JTable table = (JTable) e.getSource();
if (table.columnAtPoint(p) == 0) {
int row = table.rowAtPoint(p);
table.getSelectionModel().setSelectionInterval(row, row);
}
}
}
};
list.addMouseListener(listener);
final Container filePane = SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);
filePane.addContainerListener(new ContainerAdapter() {
#Override
public void componentAdded(ContainerEvent e) {
JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
if (table != null) {
for (MouseListener l : table.getMouseListeners()) {
if (l == listener) {
return;
}
}
table.addMouseListener(listener);
}
}
});
chooser.showOpenDialog(null);
System.exit(0);
}
}
This is how to add a delete key listener to your JFileChooser:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;
public class JFileChooserUtilities
{
public static void registerDeleteAction(JFileChooser fileChooser)
{
AbstractAction abstractAction = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
JFileChooser jFileChooser = (JFileChooser) actionEvent.getSource();
try
{
File selectedFile = jFileChooser.getSelectedFile();
if (selectedFile != null)
{
int selectedAnswer = JOptionPane.showConfirmDialog(null, "Are you sure want to permanently delete this file?", "Confirm", JOptionPane.YES_NO_OPTION);
if (selectedAnswer == JOptionPane.YES_OPTION)
{
Files.delete(selectedFile.toPath());
jFileChooser.rescanCurrentDirectory();
}
}
} catch (Exception exception)
{
exception.printStackTrace();
}
}
};
fileChooser.getActionMap().put("delAction", abstractAction);
fileChooser.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"), "delAction");
}
}
Code adapted from JavaTechnical's answer.

Create a save/save as dialog box in java that save a newly created file or an edited file

Java Beginner: Please help been working on this for days and my brain is dead.
I have created a java program (in eclipse) that has 3 menu: FILE, EDIT, HELP
once file is clicked it display 4menuBar: 'new, open,save,save as & exit.
On the HELP menu there is a menuBar that says "About javaEdit" All my menu bars work except save, save as and the "About javaEdit" I need some code or a clear step by step explanation for dummy on how to have my save and save as working.
Save should save newly created file or edited file & finally i could like the "About JavaEdit to display a message like "thank you, this is java" once clicked. I could like something like
private void doSave(){code here}
and
private void doSaveAs (){
because I have those item in the if else if statement.
How to create a save/save as dialog box in java that save a newly created file or an edited file?
Below is my entire code:
import java.awt.*;
import java.awt.event
import java.io.*;
public class JavaEdit extends Frame implements ActionListener {
String clipBoard;
String fileName;
TextArea text;
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem selectAllMI, cutMI, copyMI, deleteMI, pasteMI;
MenuItem aboutJavaEditMI;
/**
* Constructor
*/
public JavaEdit() {
super("JavaEdit"); // set frame title
setLayout(new BorderLayout()); // set layout
// create menu bar
MenuBar menubar = new MenuBar();
setMenuBar(menubar);
// create file menu
Menu fileMenu = new Menu("File");
menubar.add(fileMenu);
newMI = fileMenu.add(new MenuItem("New"));
newMI.addActionListener(this);
openMI = fileMenu.add(new MenuItem("Open"));
openMI.addActionListener(this);
fileMenu.addSeparator();
saveMI = fileMenu.add(new MenuItem("Save"));
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);
// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAllMI = editMenu.add(new MenuItem("Select all"));
selectAllMI.addActionListener(this);
cutMI = editMenu.add(new MenuItem("Cut"));
cutMI.addActionListener(this);
copyMI = editMenu.add(new MenuItem("Copy"));
copyMI.addActionListener(this);
pasteMI = editMenu.add(new MenuItem("Paste"));
pasteMI.addActionListener(this);
deleteMI = editMenu.add(new MenuItem("Delete"));
deleteMI.addActionListener(this);
// create help menu
Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
aboutJavaEditMI = helpMenu.add(new MenuItem("About JavaEdit"));
aboutJavaEditMI.addActionListener(this);
// create text editing area
text = new TextArea();
add(text, BorderLayout.CENTER);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI) {
clearText();
fileName = null;
setTitle("JavaEdit"); // reset frame title
}
else if(source == openMI) {
doOpen();
}
else if(source == saveMI) {
doSave();
}
else if(source == saveAsMI){
doSaveAs();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
}
/**
* method to specify and open a file
*/
private void doOpen() {
// display file selection dialog
FileDialog fDialog = new FileDialog(this, "Open ...", FileDialog.LOAD);
fDialog.setVisible(true);
// Get the file name chosen by the user
String name = fDialog.getFile();
// If user canceled file selection, return without doing anything.
if(name == null)
return;
fileName = fDialog.getDirectory() + name;
// Try to create a file reader from the chosen file.
FileReader reader=null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException ex) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"File Not Found: "+fileName);
dialog.setVisible(true);
return;
}
BufferedReader bReader = new BufferedReader(reader);
// Try to read from the file one line at a time.
StringBuffer textBuffer = new StringBuffer();
try {
String textLine = bReader.readLine();
while (textLine != null) {
textBuffer.append(textLine + '\n');
textLine = bReader.readLine();
}
bReader.close();
reader.close();
} catch (IOException ioe) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"Error reading file: "+ioe.toString());
dialog.setVisible(true);
return;
}
setTitle("JavaEdit: " +name); // reset frame title
text.setText(textBuffer.toString());
}
/**
* method to clear text editing area
*/
private void clearText() {
text.setText("");
}
/**
* method to copy selected text to the clipBoard
*/
private void doCopy() {
clipBoard = new String(text.getSelectedText());
}
/**
* method to delete selected text
*/
private void doDelete() {
text.replaceRange("", text.getSelectionStart(), text.getSelectionEnd());
}
/**
* method to replace current selection with the contents of the clipBoard
*/
private void doPaste() {
if(clipBoard != null) {
text.replaceRange(clipBoard, text.getSelectionStart(),
text.getSelectionEnd());
}
}
/**
* class for message dialog
*/
class MessageDialog extends Dialog implements ActionListener {
private Label message;
private Button okButton;
// Constructor
public MessageDialog(Frame parent, String title, String messageString) {
super(parent, title, true);
setSize(400, 100);
setLocation(150, 150);
setLayout(new BorderLayout());
message = new Label(messageString, Label.CENTER);
add(message, BorderLayout.CENTER);
Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
add(panel, BorderLayout.SOUTH);
okButton = new Button(" OK ");
okButton.addActionListener(this);
panel.add(okButton);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
}
}
/**
* the main method
*/
public static void main(String[] argv) {
// create frame
JavaEdit frame = new JavaEdit();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(size.width-80, size.height-80);
frame.setLocation(20, 20);
// add window closing listener
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show the frame
frame.setVisible(true);
}
}
Even an AWT program can use Action to encapsulate functionality and prevent (rather than suppress) leaking this in constructor. For example,
private static JavaEdit frame;
...
public JavaEdit() {
...
saveMI = fileMenu.add(new MenuItem("Save"));
saveMI.addActionListener(new SaveAction());
...
}
private static class SaveAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
FileDialog fDialog = new FileDialog(frame, "Save", FileDialog.SAVE);
fDialog.setVisible(true);
String path = fDialog.getDirectory() + fDialog.getFile();
File f = new File(path);
// f.createNewFile(); etc.
}
public static void main(String[] argv) {
// create frame
frame = new JavaEdit();
...
// show the frame
frame.pack();
frame.setVisible(true);
}
See HTMLDocumentEditor, cited here, for example implementations of related actions.

Disabling New Folder Button in File chooser not working properly

I disable the new Folder button using the following code:
public void disableNewFolderButton( Container c ) {
System.out.print("in disable fn");
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton)comp;
Icon icon = b.getIcon();
if (icon != null
&& icon == UIManager.getIcon("FileChooser.newFolderIcon"))
{
System.out.print("in disable fn");
b.setEnabled(false);
}
}
else if (comp instanceof Container) {
disableNewFolderButton((Container)comp);
}
}
}
The code is called in the following lines:
JFileChooser of=new JFileChooser();
of.setAcceptAllFileFilterUsed(false);
of.addChoosableFileFilter(new MyFilter());
disableNewFolderButton(of);
But the new folder button is disabled only when the file chooser is first displayed. Suppose i go to some drive , say g: , then the button is enabled again. How to set this right?
this is working for me...
//Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE);
JFileChooser fc = new JFileChooser();
Disable the "new folder" Action (which in turn will disable the button):
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class FileChooserAction
{
public static void createAndShowUI()
{
JFileChooser chooser = new JFileChooser();
BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI();
Action folder = ui.getNewFolderAction();
folder.setEnabled(false);
chooser.showSaveDialog(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
1) It is a bit stupid, but you can keep disabling it in an another Thread. Until the file chooser got invisible.
2) Does hiding the button work? b.setVisible(false);

Categories