My JFileChooser works fine without the setLookAndFeel added, and it works with it added too, but doesn't automatically become the active window. However, if I make it the active window, then close the window, then press the button that opens JFileChooser again, it becomes the active window. Here is my relevant code:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
...
JFileChooser chooser = new JFileChooser();
chooser.setVisible(true);
chooser.requestFocus(true);
chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrieval = chooser.showSaveDialog(chooser);
Thanks in advance
Related
I am trying to create a UI and run a batch file that will restart a service running in the background just by clicking a menu item. I am able to make the menu and add the menu item just like so:
JMenu menu = new("menu");
JMenuItem restart_service= new JMenuItem("Restart service");
menu .add(restart_service);
Then, I added a listener to the menu item to run the batch file:
restart_service.addActionListener (new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
openWebPage(
"file://path to bat file/batchfile.bat");
}
public void openWebPage(String url) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
});
However, everytime I try this, the cmd window pops up and prints "Access Denied". Although i changed the premission for the file to run without being admin. Not sure how to fix this or if there is a way to excute batch files as an admin by clciking a menu item. Any help would be appreciated.
Try this.
try{
Process mp = Runtime.getRuntime().exec("BAT LOC");
mp.waitFor();
}catch( Exception procRunException ){
}
Desktop desktop = Desktop.getDesktop();
File sitetxt = new File(System.getProperty("user.dir") + File.separator + "site.txt");
MenuItem settings = new MenuItem("Settings");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
desktop.open(sitetxt);
} catch (IOException e1) {
System.out.println("site.txt not found.");
e1.printStackTrace();
}
}
});
popup.add(settings);
trayIcon.setPopupMenu(popup);
I'm trying to open a text file when the user clicks "Settings" from the right click menu of the system tray icon. The default text editor is set to Notepad. There is another menu item called "Exit" but it works fine.
I'm creating a file editing app, and each file currently has its own JFrame. There are plenty of questions about making the frames fullscreen, and it works well in my app. However, I have a problem when I close the frames from fullscreen.
Normally, I set the default close operation to EXIT_ON_CLOSE. When the frame is closed, the app exits and the fullscreen space is closed, bringing me back to my desktop. However, when I leave it on HIDE_ON_CLOSE or set it to DISPOSE_ON_CLOSE (which is what I really want), closing a fullscreen JFrame leaves behind a black screen. I can still swipe between screens, see the dock and the menu bar, etc., but if there is another frame open, it will stay there until I quit the app.
Here's an example:
package net.kittycat3141.helpers;
import javax.swing.JFrame;
import net.kittycat3141.lib.util.OSXTools;
/**
* #author Kittycat3141
*/
public class MCVP_FullScreenJFrame extends JFrame {
private static final long serialVersionUID = -6467532883940003341L;
public static void main(String[] args) {
JFrame a = new MCVP_FullScreenJFrame();
OSXTools.enableFullscreen(a);
a.setVisible(true);
JFrame b = new MCVP_FullScreenJFrame();
OSXTools.enableFullscreen(b);
b.setVisible(true);
}
}
OSXTools.enableFullscreen(JFrame) does this:
if(isRunningOnMac()) {
Class util;
try {
util = Class.forName("com.apple.eawt.FullScreenUtilities");
Class params[] = new Class[]{Window.class, Boolean.TYPE};
Method method = util.getMethod("setWindowCanFullScreen", params);
method.invoke(util, frame, true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
If you run the program and make both frames fullscreen, then close one of them, you end up with a black screen. You can still swipe to other apps/desktops, etc., but it won't go away until the program is terminated.
How do I properly close the JFrame so that other frames stay open, but the black space doesn't stay there?
I'm running OS X Yosemite and Java 7.
The solution is rather long, but it works. FullScreenUtilities only has a requestToggleFullScreen method, so you need to detect whether a frame is fullscreen when it is closing and toggle it if it is.
Unfortunately, there also is no function to get whether a frame is fullscreen, so you need to attach a listener to it. The listener gets called when the frame is made fullscreen or made not fullscreen, so you can keep track of that for each frame you use. The complicated part is that everything requires reflection.
By making sure the frame isn't fullscreen by the time it closes, you avoid the black space that it leaves behind.
is there any way to save an image from a java applet
Been asked before:
Java applet - saving an image in a png format
or
Save an Image to a File in a Applet?
Please first search your question or at least check out the related questions as you type your question in. It's very helpful for finding other users with common issues.
Just try this notepad example which helps u to load images and save it also,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class Notepad extends JFrame implements ActionListener {
private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
private Menu file = new Menu(); // our File menu
// what's going in File? let's see...
private MenuItem openFile = new MenuItem(); // an open option
private MenuItem saveFile = new MenuItem(); // a save option
private MenuItem close = new MenuItem(); // and a close option!
public Notepad() {
this.setSize(500, 300); // set the initial size of the window
this.setTitle("Java Notepad Tutorial"); // set the title of the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
// this is why we didn't have to worry about the size of the TextArea!
this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
this.getContentPane().add(textArea);
// add our menu bar into the GUI
this.setMenuBar(this.menuBar);
this.menuBar.add(this.file); // we'll configure this later
// first off, the design of the menuBar itself. Pretty simple, all we need to do
// is add a couple of menus, which will be populated later on
this.file.setLabel("File");
// now it's time to work with the menu. I'm only going to add a basic File menu
// but you could add more!
// now we can start working on the content of the menu~ this
gets a little repetitive,
// so please bare with me!
// time for the repetitive stuff. let's add the "Open" option
this.openFile.setLabel("Open"); // set the label of the menu item
this.openFile.addActionListener(this);
// add an action listener (so we know when it's been clicked
this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false));
// set a keyboard shortcut
this.file.add(this.openFile); // add it to the "File" menu
// and the save...
this.saveFile.setLabel("Save");
this.saveFile.addActionListener(this);
this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
this.file.add(this.saveFile);
// and finally, the close option
this.close.setLabel("Close");
// along with our "CTRL+F4" shortcut to close the window, we also have
// the default closer, as stated at the beginning of this tutorial.
// this means that we actually have TWO shortcuts to close:
// 1) the default close operation (example, Alt+F4 on Windows)
// 2) CTRL+F4, which we are about to define now:
(this one will appear in the label)
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
this.close.addActionListener(this);
this.file.add(this.close);
}
public void actionPerformed (ActionEvent e) {
// if the source of the event was our "close" option
if (e.getSource() == this.close)
this.dispose(); // dispose all resources and close the application
// if the source was the "open" option
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser();
// open up a file chooser (a dialog for the user to browse files to open)
int option = open.showOpenDialog(this);
// get the option that the user selected (approve or cancel)
// NOTE: because we are OPENing a file, we call showOpenDialog~
// if the user clicked OK, we have "APPROVE_OPTION"
// so we want to open the file
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText("");
// clear the TextArea before applying the file contents
try {
// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext()) // while there's still something to read
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
} catch (Exception ex) { // catch any exceptions, and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
// and lastly, if the source of the event was the "save" option
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser(); // again, open a file chooser
int option = save.showSaveDialog(this); // similar to the open file, only this time we call
// showSaveDialog instead of showOpenDialog
// if the user clicked OK (and not cancel)
if (option == JFileChooser.APPROVE_OPTION) {
try {
// create a buffered writer to write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText()); // write the contents of the TextArea to the file
out.close(); // close the file stream
} catch (Exception ex) { // again, catch any exceptions and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
}
// the main method, for actually creating our notepad and setting it to visible.
public static void main(String args[]) {
Notepad app = new Notepad();
app.setVisible(true);
}
}
I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}