Having a user search and input a file in Java - java

I am working a side project that involves the user entering a file. I know there is the option for them to enter a string representing the text files name and then have the computer search for it but that would mean the file has to be in a certain location on the computer or the user has to enter the whole pathway to the file.
Is there anything similar to file input tag in HTML5 that prompts a window that allows the user to search through their laptop for the file? I've attached a picture of what I mean would be prompted on a mac.

Use file chooser by swing
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileChooserTest extends JFrame {
private JTextField filename = new JTextField(), dir = new JTextField();
private JButton open = new JButton("Open"), save = new JButton("Save");
public FileChooserTest() {
JPanel p = new JPanel();
open.addActionListener(new OpenL());
p.add(open);
save.addActionListener(new SaveL());
p.add(save);
Container cp = getContentPane();
cp.add(p, BorderLayout.SOUTH);
dir.setEditable(false);
filename.setEditable(false);
p = new JPanel();
p.setLayout(new GridLayout(2, 1));
p.add(filename);
p.add(dir);
cp.add(p, BorderLayout.NORTH);
}
class OpenL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Open" dialog:
int rVal = c.showOpenDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
class SaveL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
// Demonstrate "Save" dialog:
int rVal = c.showSaveDialog(FileChooserTest.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
dir.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText("You pressed cancel");
dir.setText("");
}
}
}
public static void main(String[] args) {
run(new FileChooserTest(), 250, 110);
}
public static void run(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
} ///:~
File dialog

Related

How to save a chosen File for the next use of the Program in Java [duplicate]

This question already has answers here:
What is the best way to save user settings in java application?
(3 answers)
Closed 2 years ago.
I am trying to save the last chosen file (by the user using JFilechooser) so that the next time the program runs, the file will be automatically opened.
public void actionPerformed(ActionEvent evt) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("xml files", "xml");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
xmlSetUp(file);
//add save file for next use
}
}
Only the accepted answer to the duplicate question mentions the Java Preferences API, but it doesn't contain any example code. The below code displays a JFrame that contains a JTextField that displays the path to the selected file as well as a JButton. When you activate the JButton, it displays a JFileChooser. Once you select a file, that selection is saved as a [java] preference. The next time you run the same application, the JTextField will initially display the path that was saved in the preferences.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Remember implements ActionListener, Runnable {
private static final String CHOOSE = "Choose";
private static final String LAST_FILE_CHOSEN = "LAST_FILE_CHOSEN";
private JFrame frame;
private JTextField textField;
private String savedFile;
#Override
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case CHOOSE:
selectFile();
break;
default:
JOptionPane.showMessageDialog(frame,
actionCommand,
"UNHANDLED",
JOptionPane.WARNING_MESSAGE);
}
}
#Override
public void run() {
showGui();
}
private JButton createButton(String text, int mnemonic, String tooltip) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(CHOOSE, KeyEvent.VK_C, "Select file."));
return buttonsPanel;
}
private JPanel createTopPanel() {
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Selected File");
topPanel.add(label);
textField = new JTextField(20);
Preferences prefs = Preferences.userNodeForPackage(getClass());
savedFile = prefs.get(LAST_FILE_CHOSEN, "");
textField.setText(savedFile);
topPanel.add(textField);
return topPanel;
}
private void selectFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File initial = new File(savedFile);
if (initial.exists()) {
fileChooser.setCurrentDirectory(initial.getParentFile());
}
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
String path = f.getAbsolutePath();
textField.setText(path);
if (!savedFile.equals(path)) {
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put(LAST_FILE_CHOSEN, path);
}
}
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Remember());
}
}

Java Swing loading image from file chooser not displaying

This is for a class assignment. I am supposed to load a file and display it on my Swing application.
I followed the process from the notes but they were vague, I also used other stackoverflow posts, but I am not able to get this to work. When I load an image the program does not crash, but nothing displays.
-Do I have to repaint or refresh the file after the image is loaded? I tried that but it did not work. what am I doing wrong? The repaint method is commented.
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Part1 {
public static File selectedFile;
public static void main(String[] args) {
JFrame frame = buildFrame();
JButton button = new JButton("Select File");
frame.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFile = fileChooser.getSelectedFile();
CardImagePanel image = new CardImagePanel(selectedFile);
frame.add(image);
// frame.repaint();
}
}
});
}
private static JFrame buildFrame()
{
JFrame frame = new JFrame();
frame.setSize(1000,1000);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
}
class CardImagePanel extends JPanel {
private BufferedImage image;
public CardImagePanel(File newImageFile)
{
try {
image = ImageIO.read(newImageFile);
} catch (IOException e){
e.printStackTrace();}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 500, 500, this);
}
}
As was mentioned, you need to call frame.revalidate(); after you add the new component.
You also should call image.setPreferredSize(new Dimension(500, 500)); or similar to ensure that your image isn't tiny.

I need a Jlist to popup when a file with integers is either entered or selected from JFileChooser

I am using WindowBuilder in Eclipse to aid in my GUI design. I am trying to make a Jlist popup after the user either enters in a text file with integers in it or, if they enter a file that doesn't exist, they select a file with integers in it from JFileChooser. My problem I am having now is that when the file is selected, nothing happens. The program also doesn't seem to recognize when I do enter in a file that exists, it just defaults to the JFileChooser. Any ideas as to what I'm doing wrong and/or how to make the Jlist appear after an appropriate file is entered?
Here is the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI {
private JFrame frame;
private JTextField txtEnterFileName;
private JTextField textField;
private JFileChooser fileChooser;
private JList list;
private JList list_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtEnterFileName = new JTextField();
txtEnterFileName.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtEnterFileName.setEditable(false);
txtEnterFileName.setText("Enter File Name Below and Press Button");
txtEnterFileName.setBounds(72, 11, 304, 41);
frame.getContentPane().add(txtEnterFileName);
txtEnterFileName.setColumns(10);
textField = new JTextField();
textField.setBounds(113, 63, 221, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int number;
boolean endOfFile = false;
File userF;
userF = new File(textField.getText());
if(!userF.exists()){
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "/desktop"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(userF.exists()){
try {
Scanner inFile = new Scanner(userF);
if(inFile.hasNextLine()){
inFile.close();
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(inFile.hasNextInt()){
String label[] = {"Smallest Number", "Largest Number", "Count", "Average", "Median", "Quit"};
list = new JList(label);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
btnNewButton.setBounds(174, 99, 89, 23);
frame.getContentPane().add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Scanner#nextLine always seems to return true so long as there some text on the first line.
So a file in the format of ...
1 2 3 4 5 6
Will have Scanner#nextLine return true. Instead, you should check for hasNextInt first and then skip over to showing the JFileChooser
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

why BufferedImage does not show full image in JLabel?

I am getting files from JFileChooser and showing them by reading with BufferedImage and putting in JLabels but there is a problem that my images are not completely shown in JLabels. Here is my code
public class ImagePreview
{
JPanel PicHolder= new JPanel();
public ImagePreview()
{
JButton GetImages = new JButton("Browse Images");
GetImages.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
CreatePreviews();
};
});
PicHolder.add(GetImages);
JFrame MainFrame = new JFrame("Image Preview");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(PicHolder);
MainFrame.pack();
MainFrame.setVisible(true);
}
public void CreatePreviews()
{
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
File[] selectedCarImages = chooser.getSelectedFiles();
for(int a=0; a<selectedImages.length; a++)
{
try
{
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
PicHolder.add(picLabel);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}
When I run this code, it shows user selected images but they are kind of automatically croped and not showing completely in JLabels.
What's wrong here? Why JLabels do not show full images?
You're adding all the components and images to a single panel having the default FlowLayout. Instead, use GridLayout for the picture labels and add the browse button to the frame's default BorderLayout, as shown below.
As tested:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImagePreview {
JFrame mainFrame = new JFrame("Image Preview");
JPanel picHolder = new JPanel(new GridLayout(0, 1));
public ImagePreview() {
JButton getImages = new JButton("Browse Images");
getImages.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
CreatePreviews();
}
});
mainFrame.add(getImages, BorderLayout.NORTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new JScrollPane(picHolder));
mainFrame.pack();
mainFrame.setLocationByPlatform(true);
mainFrame.setVisible(true);
}
public void CreatePreviews() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(mainFrame);
File[] selectedImages = chooser.getSelectedFiles();
for (int a = 0; a < selectedImages.length; a++) {
try {
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picHolder.add(picLabel);
mainFrame.pack();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}

Adding an int per click (java)

I am making a "fake virus" in java. when you run it a window called "Your computer has a virus" pops up and the window has a button that says "Your computer has (1) viruses. Click here to uninstall them" but when you click it one more window pops up. but i want it to be like each time you click it the number of "viruses" is added 1 to. (For example the second window that pops up after clicking button says "Your computer has (2) viruses"). I have tried to add it but it didn't work. (sorry for my terrible grammar). Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FirstWindow extends JFrame {
int virusAmount = 1;
private static final long serialVersionUID = 1L;
public FirstWindow(){
super("Your computer has a virus");
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b = new JButton("Your computer has (" + virusAmount++ + ") virus(es). Click here to uninstall them.");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow();
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}
Just define it in the constructor:
public FirstWindow(int i){}
Full example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FirstWindow extends JFrame {
int virusAmount;
private static final long serialVersionUID = 1L;
public FirstWindow(int i) {
virusAmount = i;
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b;
if(virusAmount == 1){
b = new JButton("Your computer has a virus");
}
else{
b = new JButton("Your computer has (" + virusAmount + ") virus(es). Click here to uninstall them.");
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow(virusAmount+1);
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}
public class Main {
public static void main(String[] args) {
FirstWindow fw = new FirstWindow(1);
fw.setVisible(true);
}
}

Categories