So here is te thing, Im trying to do an Applet for a webgame to produces "custom" avatars, this avatar are for a kind off an army of a country, so the avatar cosnsit on the image of the choice of the user, and a frame on the picture thtat represent the quad that the user belongs too.
So my plan is to make them choose from a file from their computer, and then they choose the squd that they belong to. After this they will see a preview of the picutre and they can save it to their computer to later use it on the game.
I know that you can draw image with a Graphic or Graphic2D on the background of a component, but then when I want to save it to a file, How I do that?
Use JFileChooser#showSaveDialog() to ask user to select/specify a file to save and then use ImageIO#write() to write the BufferedImage to the file.
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
ImageIO.write(bufferedImage, "JPEG", fileChooser.getSelectedFile());
} else {
// User pressed cancel.
}
The applet needs however to be signed to avoid the enduser being scared by security warnings.
Digital code signing is not required for an applet deployed using a Plug-In 2 (PI2 - 1.6.0_10+) architecture JRE. In a PI2 JRE, an embedded applet can access all the services normally only available to Java Web Start apps.
The services of interest to this applet would be the FileOpenService (FOS), and the PersistenceService (PS). The FOS could be used to allow the user to navigate to a File (or rather - a FileContents) object and obtain streams from it. Once the user is happy with the cropped image, save in to the PS for later retrieval (using ImageIO, as already mentioned).
here is the notepad code where u can save the contents and also if u convert the text into an image.so try going through it
/*Arpana*/
mport 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 think I'd be inclined to interact the Java with Javascript on the same page, and give an 'export' button which serialises it to PNG locally, and offers it as a download (should be possible all without the user needing to refresh the page or mess around). There are some interesting comments in this previous question: Java applet - saving an image in a png format
The notepad program which i have posted just above this post gives the load image of any type and also to save image of any type....
so you cab refer the same code to load the image and save the image
Related
I am creating a notepad in java for a class assignment. I have created the text box with the File, Edit, Print, Help buttons with drop downs to do various options, I need help with the color change, font change, sent to printer and the hyperlinks under help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class MyMenuFrame extends JFrame implements ActionListener {
private TextArea textArea = new TextArea("", 0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
// first, create a MenuBar item
private MenuBar menuBar = new MenuBar();
private Menu file = new Menu();
private Menu edit = new Menu();
private Menu print = new Menu();
private Menu help = new Menu();
// File objects
// open option
private MenuItem open = new MenuItem();
// save option
private MenuItem save = new MenuItem();
// close option!
private MenuItem close = new MenuItem();
// Edit objects
// color option
private MenuItem color = new MenuItem();
// font option
private MenuItem font = new MenuItem();
// print object
private MenuItem printSend= new MenuItem();
// help objects
private MenuItem about= new MenuItem();
private MenuItem home=new MenuItem();
public MyMenuFrame() {
// set the initial size of the window
this.setSize(600, 400);
// set the title of the window
this.setTitle("MyNotepad");
// set the default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
// set a default font for the TextArea
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12));
// 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);
this.menuBar.add(this.edit);
this.menuBar.add(this.print);
this.menuBar.add(this.help);
// create file drop down menu
this.file.setLabel("File");
// create open option
this.open.setLabel("Open");
//action listener to know when it's been clicked
this.open.addActionListener(this);
// keyboard shortcut
this.open.setShortcut(new MenuShortcut(KeyEvent.VK_O, false));
// add it to the "File" menu
this.file.add(this.open);
// create save option
this.save.setLabel("Save");
//action listener to know when it's been clicked
this.save.addActionListener(this);
// keyboard shortcut
this.save.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
// add it to the "File" menu
this.file.add(this.save);
// create close option
this.close.setLabel("Exit");
// action listener to know when it's been clicked
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_X, false));
// keyboard shortcut
this.close.addActionListener(this);
// add it to the "File" menu
this.file.add(this.close);
// create edit drop down menu
this.edit.setLabel("Edit");
this.edit.addActionListener(this);
this.color.setLabel("Color");
this.font.setLabel("Font");
this.color.setShortcut(new MenuShortcut(KeyEvent.VK_C,false));
// color and font change buttons added
this.edit.add(this.color);
this.edit.add(this.font);
// print menu
this.print.setLabel("Print");
this.print.addActionListener(this);
this.printSend.setLabel("Send to Printer");
// send to printer button and shortcut keys added
this.print.add(this.printSend);
this.printSend.setShortcut(new MenuShortcut(KeyEvent.VK_P,false));
// help menu
this.help.setLabel("Help");
this.about.setLabel("About");
this.home.setLabel("Visit Home");
this.about.setShortcut(new MenuShortcut(KeyEvent.VK_A,false));
this.home.setShortcut(new MenuShortcut(KeyEvent.VK_H,false));
this.help.addActionListener(this);
// about and homepage buttons added
this.help.add(this.about);
this.help.add(this.home);
}
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.open) {
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) {
// clear the TextArea before applying the file contents
this.textArea.setText("");
try {
// create a scanner to read the file
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
// while there's still something to read
while (scan.hasNext())
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
}
catch (Exception ex) { // catch any exceptions
//write to the debug console
System.out.println(ex.getMessage());
}
}
}
//if the source of the event was the "save" option
else if (e.getSource() == this.save) {
//open a file chooser
JFileChooser save = new JFileChooser();
// similar to the open file, only this time we call
int option = save.showSaveDialog(this);
// showSaveDialog instead of showOpenDialog
// if the user clicked OK
if (option == JFileChooser.APPROVE_OPTION) {
try {
// create a buffered writer to write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
// write the contents of the TextArea to the file
out.write(this.textArea.getText());
// close the file stream
out.close();
}
catch (Exception ex) { //catch any exceptions
//write to the debug console
System.out.println(ex.getMessage());
}
}
}
else if(e.getSource()==this.color){
}
else if(e.getSource()==this.font){
JFileChooser font= new JFileChooser();
}
else if(e.getSource()==this.printSend){
JFileChooser printSend= new JFileChooser();
}
else if(e.getSource()==this.about){
JFileChooser about= new JFileChooser();
}
else if(e.getSource()==this.home){
JFileChooser home= new JFileChooser();
}
}
}
public class MyMenuFrameTest {
public static void main(String args[]) {
MyMenuFrame notePad = new MyMenuFrame();
notePad.setVisible(true);
}
}
These are the parameters my professor has specified.
a. The title of the frame is “MyNotepad”.
b. Create and add border layout.
c. Create a text area to display contents. Add the text area to the center of the border layout.
d. Create a menu bar.
e. Create a file menu. Set mnemonic for file menu. It is “F”. File menu includes three menu items.
f. Add a separator between each menu item in the file menu.
i. Open 1. Add a short cut for the menu item. It is ctrl+O.
a. Use this syntax: MenuItem.setAccelerator(KeyStroke.getKeyStr oke('O', CTRL_DOWN_MASK));
2. When a user clicks it (an action event occurs) a file chooser is created, and an open dialog box is opened. The user selects a text file to open it and then clicks “Open” or the user can click on “Cancel”. Use try block with resources. (Hint: add catch block automatically, click add catch clause).
ii. Save 1. Add a short cut for the menu item. It is ctrl+S.
2. When a user clicks it (an action event occurs) a file chooser is created, and a save dialog box is opened. The user writes the name of text file to save it and then clicks “Save” or the user can click on “Cancel”. User try block with resources. (Hint: add catch block automatically, click add catch clause).
iii. Exit 1. Add a short cut for the menu item. It is ctrl+X.
2. When a user clicks it (an action event occurs), it terminates the application. g. Create edit menu. Set mnemonic for file menu. It is “D”. Edit menu includes two menus: Color and Font. h. Add a separator between each sub menu.
i. Create color menu. Set mnemonic for file menu. It is “C”. i. Create change color menu item. Add a short cut for the menu item. It is ctrl+C.
ii. When a user clicks change color, a color chooser is opened, and the user selects a color. By default, red color is selected. Then, the color of the text is changed.
j. Create font menu. Set mnemonic for file menu. It is “F”.
i. This menu includes three radio button menu items: Times New Roman, Arial, Serif. (Hint: you also need a button group). When a user selects one of these fonts (an action event occurs), the font of the text will change. Set font size as 20.
ii. This menu includes also two check box menu items: Bold, Italic. A User can select both, only bold one, italic one, or unselect any of them (an item event occurs). Based on the user selection, set the font. (Hint: if one of them is unselected, set the font as plain). Set font size as 20.
iii. Add a separator between radio button menu items and check box menu items.
k. Create Print menu. Set mnemonic for print menu. It is “P”. i. Printer menu includes one menu item: Send to Printer. Add a short cut for the menu item. It is ctrl+P.
ii. When a user clicks it (an action event occurs), display an Option Dialog. Display the message in the figure. If the user clicks “Ok”, display a message dialog box (set information icon). Display the message in the figure. If the user clicks cancel, make the current frame as visible.
l. Create a help menu. Set mnemonic for help menu. It is “H”. m. Help menu includes two menu items: About, Visit Homepage. Add a separator between these menu items.
i. Create a menu item which is about. Add a short cut for the menu item. It is ctrl+A.
When a user clicks it (an action event occurs), display a show message dialog box. Display the message shown in the figure. Display information icon.
ii. Create a menu item which is visit homepage. Add a short cut for the menu item. It is ctrl+V.
1. When a user clicks it (an action event occurs), the user will be navigated to http://www.microsoft.com.
2. For the navigation, create a static method (copy it):
public static void openWebpage (String urlString) {
try { Desktop.getDesktop().browse(new URL(urlString).toURI()); }
catch (Exception e) { e.printStackTrace(); } }
Then in the action performed method, call this static method and provide the url String.
n. When it is necessary, import the necessary classes and interfaces.
o. Set frame as 600*400.
By design, a JTextArea uses one font and one color. Use JTextPane instead.
As for your font and color menu actions, use the JTextPane’s getStyledDocument() method.
You’ll need to create an AttributeSet for each action. If you look at the documentation, you’ll see many implementing classes. Among them is SimpleAttributeSet, which is sufficient for your needs. Rather than setting its attributes directly, use the methods of StyleConstants.
Printing is as simple as calling the inherited print() method.
Needless to say, you should remove the use of JFileChooser from any action which doesn’t actually need to read or write a file.
OK SO I'm doing a project for class and I've gotten what I need to work working (For now.) What I want to do now is when I click a button a the gui it displays all the data in the Text Pane. So far all it does is print out Grades (Which I understand why) But I want it to print out what is being parsed in the CSV Files. I'm not asking for anyone to magically solve my entire code I have most of that down, I just don't know how to make the button actually display the desired results and it's making me mad because I finally got the code to do what I wanted but I can't see the results. (It works in the Console but when the .jar is run nothing is displayed.)
The Question has been answered Read comments below. Code has been removed. Thank you for your time!
You shouldn't create a new JTextPane everytime your JButton was clicked. Add the pane once to the JFrame and in your ActionListener just set the value via setText:
You never set the content of your csv file to your JTextPane via setText: but you only print it out via System.out.println("Student - " + grades[0] + " "+ grades[1] + " Grade - " + grades[2]);
Here I made you an example. The example doesn't really base on your posted code since it would have been to much effort to look into your whole code and correct it, but it shows everything you need to do in order to make your code work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Instructor {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new BorderLayout());
final JTextPane textPane;
textPane = new JTextPane();
frame.add(textPane,BorderLayout.CENTER);
JButton button = new JButton("Read CSV");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Reset textpanes content so on every button click the new content of the read file will be displayed
textPane.setText("");
String fileResult = "";
try {
BufferedReader csvReader = new BufferedReader(new FileReader("myCSV.csv"));
String line = null;
while ((line = csvReader.readLine()) != null) {
//Do your logic here which information you want to parse from the csv file and which information you want to display in your textpane
fileResult = fileResult + "\n" +line;
}
}
catch(FileNotFoundException ex) {
System.err.println("File was not found");
}
catch(IOException ioe) {
System.err.println("There was an error while reading the file");
}
textPane.setText(fileResult);
}
});
frame.add(button,BorderLayout.SOUTH);
frame.setVisible(true);
}
}
So what did I do:
Create JTextpane not in the ActionListener but once
Read the file in the ActionListener and provide try and catch in order to make sure there is some error handling when the file can't be found or something like this.
Don't print the results of the csv via System.out.println(); but set the results to the JTextPane by calling the setText: method.
I also added a LayoutManger (BorderLayout) instead of adding the JTextPane and the button to the JFrame with NullLayout. This isn't part of the question but if you got time you should change this, since the NullLayout isn't recommended at all (setBounds in your code).
I am having some trouble in ImageJ with one of its files. Basically set up a desktop pane that analyzes and opens images. But when the program opens the image it opens it as a separate JFrame. I would like to be an internal JFrame. So basically the image opens up in the desktop pane. I have tried a couple of things like creating a internal frame class and adding the win to the desktopPane but nothing seems to work it still opens it as a separate JFrame. I was wondering if anyone knows how to do this.
This is my code (this function is just calling .show() to display the image, the code for the actual JFrame that opens the window is in ImageWindow.java):
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
FileOpener open = new FileOpener(file);
ImagePlus fopen = open.open(false);
if(fopen != null){
BufferedImage openImage = fopen.getBufferedImage();
new ImagePlus(path,openImage).show(desktop); //This functions displays the image
ImagePlus newImage = new ImagePlus(path,openImage);
img = newImage;
}
frame.setVisible(false);
}
The creation of a new JFrame is hardcoded into ImageJ's ImagePlus class:
if (stackSize>1)
win = new StackWindow(this);
else
win = new ImageWindow(this);
If you want to adapt the GUI, you can extend the ImageWindow or StackWindow classes. See the Trainable Weka Segmentation plugin for a nice example.
Alternatively, use the data structures of ImageJ2, namely ImgLib's ImgPlus. These are designed to be independent of any user interface.
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
add(menubar,BorderLayout.NORTH);
menubar.add(file);
JMenuItem Open = new JMenuItem("OPEN... Ctrl+O");
file.add(Open);
Open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Frame f = new Frame();
FileDialog openf = new FileDialog(f, "Open");
openf.setVisible(true);
}
});
Well, I tried to use a lot many examples on the internet which makes the open button work as you can see i have already made the design but i need help in how to open a .txt file on clicking the open button in the filedialog. how am i supposed to do that?? i would really appreciate if anyone can help me out with few lines of code that actually works as i am sick of searching error generating codes from the internet.
The documentation states:
The FileDialog class displays a dialog window from which the user can
select a file.
Since it is a modal dialog, when the application calls its show method
to display the dialog, it blocks the rest of the application until the
user has chosen a file.
Therefore, instead of calling .setVisible(true) you can call .show() on the dialog, and then you can use getFile() to get the file that was chosen, or getFiles() if you are using multipleMode.
To read the file you can use:
public static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
yourComponent.setText(readFile(openf.getFile(), Charset.defaultCharset()));
(Taken from this question)
I am trying to put a JFileChooser box on my GUI but if I just do this
JFileChooser filechooser = new JFileChooser ();
then it will just show a huge file selection window on the panel (I do not want that), so I want to make a small box filechooser (with a name for example "choose file") that when I click it, a window will popup, so then I can choose the file.
Use a button to open your file chooser and use setPreferredSize() method to make the file chooser smaller in size:
JButton button = new JButton("Choose a file!");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle( "Choose a file" );
fileChooser.setVisible( true );
fileChooser.setPreferredSize( new Dimension(100, 100) );
}
});
Call
filechooser.setPreferredSize (new java.awt.Dimension (800, 800));
before calling showOpenDialog with whatever Dimension you like.
But I would suggest to either maximize the Dialog, because in the moment I like to open a File, I don't like to watch something else - find a file, and close the dialog, without much scrolling, because somebody thought it looks more nice.
If you like to prevent wasting space, you can precalculate the needed size for the window, which might be a lot of work, but could pay off, if you use the Component frequently.