saving an image from applet - java

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);
}
}

Related

IntelliJ debugger does not stop after adding JFileChooser to my project

Synopsis
I am developing a Java Swing project, and I have been debugging successfully within IntelliJ IDEA by running the main method directly. After closing the frame, the debugger exits normally.
However, after adding a JFileChooser dialog to the project, the debugger does not exit normally. I have to click the stop button every time now, which causes the JVM to exit with a non-zero status.
Minimal, Reproducible Example
This is the section of code that is causing the problem; it is an ActionListener that I am adding to two buttons which launch the JFileChooser:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
final int result = fileChooser.showOpenDialog(new JFrame());
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
Debugging Steps
I have tried moving the JFrame creation from the parameter of the showOpenDialog method to a variable declaration and added frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); but that did not fix the issue. It's almost like the frame is still hanging around in memory, and that's why the JVM won't close.
Question
How can I make the JVM close appropriately while using JFileChooser?
The problem is, indeed, that the JFrame is still in memory, causing the JVM to hang. However, the solution is a JFrame is not needed.
Instead of setting a new JFrame() as the parent of the dialog, set the parent to the dialog window itself:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
--> final int result = fileChooser.showOpenDialog(fileChooser); <--
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
Change the line where you get the result: final int result = fileChooser.showOpenDialog(fileChooser);. Doing that fixes the issue.

Add a button menu to javahelp

In my program, I'm using javahelp with helpbroker: all the swing components of the window are automatically generated and positioned.
I would like custom the helpbroker to add a button bar at the bottom of the window like in the image.
What is the easiest way to do it ?
Thanks
The only way to add a help button is to Embed the javahelp in a JFrame:
public class vmHelp {
public static void main(String args[]) {
JHelp helpViewer = null;
String title = "";
try {
// Get the classloader of this class.
ClassLoader cl = vmHelp.class.getClassLoader();
// Use the findHelpSet method of HelpSet to create a URL referencing the helpset file.
// Note that in this example the location of the helpset is implied as being in the same
// directory as the program by specifying "jhelpset.hs" without any directory prefix,
// this should be adjusted to suit the implementation.
String lHelpSetFile = "APP.hs";
URL url = HelpSet.findHelpSet(cl, lHelpSetFile);
if (url == null) {
System.err.println("URL is null, maybe the help set file is wrong: " + lHelpSetFile + ". Look at vmHelp.java");
return;
}
// Create a new JHelp object with a new HelpSet.
HelpSet h = new HelpSet(cl, url);
title = h.getTitle();
helpViewer = new JHelp(h);
// Set the initial entry point in the table of contents.
helpViewer.setCurrentID("top");
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Create a new frame.
JFrame frame = new JFrame();
// Set it's size.
frame.setSize(1000, 800);
// Add the created helpViewer to it.
frame.getContentPane().add(helpViewer);
// Set a default close operation.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(title);
// Make the frame visible.
frame.setVisible(true);
}
}
After we can customize the JFrame as we want, it is easy to add a south panel with a close button.
To make all the help buttons listen our javahelp:
pButton.addActionListener(helpAction(pHelpId));
with helpAction that displays our JFrame
Think also to handle keyboard shortcuts, like the helpbroker:
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
To open the help at the wanted section:
helpViewer.setCurrentID("top");
"top" corresponds to tag in the .jhm file

Add an event for button

I have jbutton1 which has a text "Connect" when the user clicks the jbutton1 the application runs and the text of jbutton1 changes from "Connect" to "Disconnect". Now again when the user clicks jbutton1 and the text is "Disconnect" so the application should close.
The code i have given here does not checks anything it automatically closes the application which i don't want. I want to check the text of the button if it is connect i should do a different process and if it is disconnect it shouls close my application when the button is clicked.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jComboBox2.getSelectedItem()==null)
{
System.out.println("Select one name");
}
else
{
try {
Runtime r = Runtime.getRuntime();
p = Runtime.getRuntime().exec("C:\\Program Files");
AS a4sObj = new AS(new String[]{jComboBox2.getSelectedItem().toString()});
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
Just move setText to the end:
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
This is wrong
if(jButton1.getText()== "Disconnect") , take a look at this great answer to check the reason and learn how to compare Strings in java
You should do:
if("Disconnect".equalsIgnoreCase(jButton1.getText()))
instead

how to close visibility of "create new folder" in jfilechooser

I have aimed to close "create new folder" button on the file chooser. Is it possible to set visibility of "create new folder" button on the file chooser ? I can set visibility of first component which row start with "look in" words to off but I want set visibility of only "create new folder" not all of them. How can I do that ?
Two suggestions:
You can make the button disabled by accessing the default Action and disabling the Action:
Action folder = fileChooser.getActionMap().get("New Folder");
folder.setEnabled( false );
Or you can use reflection to access the button and make the button invisible:
//JButton button = SwingUtils.getDescendantOfType(
// JButton.class, fileChooser, "ToolTipText", "Create New Folder");
//button.setVisible(false);
For this approach you will need to use the Swing Utils class.
Here is a quick demo showing both approaches:
import java.awt.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
JFileChooser fileChooser = new JFileChooser();
Action folder = fileChooser.getActionMap().get("New Folder");
folder.setEnabled( false );
// Make the button invisible
//JButton button = SwingUtils.getDescendantOfType(
// JButton.class, fileChooser, "ToolTipText", "Create New Folder");
//button.setVisible(false);
fileChooser.showOpenDialog(null);
}
}
I have used icon name to close buttons. My implementation is ;
JFileChooser fileChooser = new JFileChooser();
// operations related with adjusting JFileChooser user interface
closeButton(fileChooser, "FileChooser.newFolderIcon");
closeButton(fileChooser, "FileChooser.upFolderIcon");
Main function which is going to be called to dis-appear buttons on user interface
void closeButton(JFileChooser fileChooser, String label){
Icon icon = UIManager.getIcon(label);
closeButtonHelper(fileChooser.getComponents(), icon);
}
void closeButtonHelper(Component[] containers, Icon icon) {
for(Object iterator:containers){
if(iterator instanceof JButton){
Icon temp = icon.getIcon();
if(temp != null && temp == icon){
(JButton.class.cast(iterator)).setVisible(false);
}
} else
if(iterator instanceof Container){
doVisibleHelper(Container.class.cast(iterator).getComponents(), icon);
}
}
}
For toggle button, just add new if-then-else statement, like;
if(iterator instanceof JToggleButton){
Icon temp = icon.getIcon();
if(temp != null && temp == icon){
(JToggleButton.class.cast(iterator)).setVisible(false);
}
} else

Hows to open an .bmp/.jpeg image using Java

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)
{
}

Categories

Resources