Size of JFilechooser - java

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.

Related

Image doesn't show in image button

I have create an image button but it didn’t show the image. The file is on src\MyPackage folder. How can I map it?
There is my code:
jpAnnotation=new JPanel();
jpAnnotation.setLayout(new FlowLayout(FlowLayout.LEADING));
JButton btnUnderline =new JButton(new ImageIcon ("UnderlineIcon.gif"));
btnUnderline.setSize(50, 260);
btnUnderline.setAlignmentX(JButton.LEFT_ALIGNMENT);
btnUnderline.setHorizontalAlignment(JButton.LEFT);
btnUnderline.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
ActionEvent ae = new ActionEvent(bean, 0, "Underline");
bean.actionPerformed(ae);
}
});
jpAnnotation.add(btnUnderline);
Just a little code snippet:
btnUnderline.setIcon(
new ImageIcon(getClass().getResource("/path/to/UnderlineIcon.gif")));
Brief explanation
Using this statement for loading your image, you don't have to care about the right URL to your file, because you automatically get the correct URL.
This is based on loading the resource from the class path and not from the filesystem path!
Try this:
btnUnderline.setIcon( new ImageIcon( "C:\\YourFolder\src\MyPackage\UnderlineIcon.gif" ) );
If of course you're using Windows. Alternatively you can move the gif to the same directory as where you're executing your code from.

What method is used to make the open button in FileDialog work?

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)

Save an Image to a File in a Applet?

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

How to open JFileChooser with predefined size

chooser = new JFileChooser();
chooser.setSize(300, 200);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
.......
}
This doesn't work.
Always opens in default size.
Try chooser.setPreferredSize(new Dimension(300, 200))
Maybe a solution would be to extend the JFileChooser class and overload the constructor with the new setSize method. Not sure if this will work. I know you can extend the very basic JDialog to create custom dialogs and calling setSize there worked for me last time I tried it.

Customizing javax.swing.JFileChooser to include an additional JTextField

I want to include an additional (optional) JTextField in the FileChooser, allowing the user to fill it in while choosing the file rather than giving them an additional prompt after they make their choice. Has anybody attempted something similar and found a working solution?
My target result would look something like this:
The documented way to add controls to a JFileChooser is via the setAccessory(JComponent) method.
JTextField field = new JTextField("Hello, World");
JPanel accessory = new JPanel();
accessory.setLayout(new FlowLayout());
accessory.add(field);
JFileChooser chooser = new JFileChooser();
chooser.setAccessory(accessory);
int ret = chooser.showOpenDialog(frame);
However, this will layout the new control on the right of the dialog (exact positioning is probably locale-dependent).
To locate the component to the position you want it, you'll probably have to walk the component graph and manipulate it. This would be a very fragile approach and you may be better off just building your own dialog.
This could incorporate a file chooser:
JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO - wire into something
System.out.println(e);
}
});
JTextField field = new JTextField("Hello, World");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(chooser, BorderLayout.CENTER);
panel.add(field, BorderLayout.SOUTH);

Categories