I have write a class filechooser where I can choose files. I had searched for a class that loads images but nothing. My filechooser class can made a panel with button open and save. When I press button open I can search in my documents and when I'm going to open the image my image load class not responding I need some class that can synchronize with me filechooser and load my image from my documents and show it in the panel.
package project;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
public class FileChooserDemo extends JPanel
implements ActionListener {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
public FileChooserDemo() {
super(new BorderLayout());
//Create the log first, because the action listeners
//need to refer to it.
log = new JTextArea(5,20);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
//Create a file chooser
fc = new JFileChooser();
openButton = new JButton("Open a File...");
openButton.addActionListener(this);
//Create the save button. We use the image from the JLF
//Graphics Repository (but we extracted it from the jar).
saveButton = new JButton("Save a File...");
saveButton.addActionListener(this);
//For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel(); //use FlowLayout
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
//Add the buttons and the log to this panel.
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
}
log.setCaretPosition(log.getDocument().getLength());
//Handle save button action.
} else if (e.getSource() == saveButton) {
int returnVal = fc.showSaveDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would save the file.
log.append("Saving: " + file.getName() + "." + newline);
} else {
log.append("Save command cancelled by user." + newline);
}
log.setCaretPosition(log.getDocument().getLength());
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
public static void createLoad() {
//Create and set up the window.
JFrame frame = new JFrame("FileChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new FileChooserDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
this is the class file chooser i need a class that can load the picture i open
and this is the imageload code.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
/**
* This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public LoadImageApp() {
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
}
}
what i want is the image code read the file.aboslutepath and load the picture when i click it
To get the selected file you should use the getSelectedFile after JFileChooser stop.
To display it:
You can also use a component wich render a Image on it.
This one I made and is under my project is a JPanel extension and let you add components on it (over image)
https://github.com/MarkyVasconcelos/Towel/wiki/JImagePanel
All the file choose is used for is to get the name of the file you want to load. You still need to load the file.
Start by reading the section from the Swing tutorial on How to Use Icons for example code on how to read the image.
Related
Well, the only problem I am having is that the open dialog is showing first. What I want is to only to put it inside the JFrame and then do the rest inside the JFrame like opening image and display it. It should be like this
The problem is that my JFileChooser is showing first. And also the thing is I want it all to be inside the JFrame just like in the image shown.
Here is my code:
import java.awt.Image;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.*;
import java.awt.Color;
import java.awt.Dimension;
public class imgviewer extends JFrame{
JButton button;
JLabel label;
public imgviewer() {
super("Image viewer");
label = new JLabel();
label.setBounds(400, 10, 180, 300);
Border b = BorderFactory.createLineBorder(Color.ORANGE, 2);
JFileChooser file = new JFileChooser(".");
label.setBorder(b);
add(label);
file.setPreferredSize(new Dimension(400, 300));
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif");
file.addChoosableFileFilter(filter);
int result = file.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
label.setIcon(ResizeImage(path));
}
else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No File Selected");
}
add(file);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600, 350);
setVisible(true);
}
public ImageIcon ResizeImage(String ImagePath) {
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args) {
new imgviewer();
}
}
I'm not sure how to do what you want to do, but where you put the line int result = file.showOpenDialog(null); into your code, that's a line that explicitly means "open this JFileChooser in its own file dialog NOW". In the order of your code, that clearly happens before the setVisible(true) line which would open the wrapper you wish to put around the file dialog.
Is there a reason the code after file.addChoosableFileFilter(filter);, and before add(file), is indented? If you were imagining that this code is in a separate block which will prevent it from being executed until later, it isn't.
I haven't worked with JFileChooser, or Swing in general, for a long time now, so I don't know off hand how well a JFileChooser will work if treated as a separate component embedded inside another component, but if that's going to work at all, you definitely cannot use JFileChooser's showOpenDialog method.
I am reading from a file that will have tons of lines of text and I want my program to read all of the lines in that file and output them in the same format onto either a JLabel or anything that would work.
public String readSoldTo() {
String file = "/Users/tylerbull/Documents/JUUL/Sold To/soldTo.txt";
String data;
try{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((data = br.readLine()) != null) {
System.out.println(data);
return data;
}
br.close();
}catch(Exception e) {
}
return file;
}
A JLabel is built to display one line of text. Yes you can jury-rig it to show more, but that's a kludge and can often cause future problems in your code. Instead I would suggest that you display your text in a JTextArea, and you can make it so that it looks like a JLabel by removing its border by making its background color null. If you add it to a JScrollPane though, you'll see scrollbars (if appropriate) and the scrollpane's border, which may be a problem. I would also make the JTextArea non-focusable and non-editable, again so that it acts more like a label and less like a text component that accepts user interaction.
Also JTextComponents, like JTextFields have mechanisms that allow you pass it a reader so that it can participate in the reading of the text file, preserving line breaks if desired. Please see its read method API entry for more on this. As always, take care to respect Swing threading rules, and do your text I/O in a background thread, and all Swing mutation calls on the Swing event thread.
Your code also worries me some:
You seem to be ignoring exceptions
You have two returns in your method above, and both return two vastly different bits of information.
For example:
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
#SuppressWarnings("serial")
public class TextAreaAsLabel extends JPanel {
private static final int TA_ROWS = 30;
private static final int TA_COLS = 50;
private static final Font TA_FONT = new Font(Font.DIALOG, Font.BOLD, 12);
private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);
public TextAreaAsLabel() {
// JButton and JPanel to open file chooser and get text
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new ReadTextAction("Read Text")));
// change JTextArea's properties so it "looks" like a multi-lined JLabel
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setBackground(null);
textArea.setBorder(null);
textArea.setFocusable(false);
textArea.setEditable(false);
textArea.setFont(TA_FONT);
// add components to *this* jpanel
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private class ReadTextAction extends AbstractAction {
public ReadTextAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// create file chooser and limit it to selecting text files
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fileChooser.setFileFilter(filter);
fileChooser.setMultiSelectionEnabled(false);
// display it as a dialog
int choice = fileChooser.showOpenDialog(TextAreaAsLabel.this);
if (choice == JFileChooser.APPROVE_OPTION) {
// get file, check if it exists, if it's not a directory
File file = fileChooser.getSelectedFile();
if (file.exists() && !file.isDirectory()) {
// use a reader, pass into text area's read method
try (BufferedReader br = new BufferedReader(new FileReader(file))){
textArea.read(br, "Reading in text file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TextAreaAsLabel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
After choosing a file in JFileChooser I want JTextField to be appended with the path to it. I wrote the following code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
public class Program extends JFrame{
public static void main(String[] args){
new Program();
}
public Program(){
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("Projekt Java");
JPanel thePanel = new JPanel();
thePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton button1 = new JButton("Wybierz plik:");
JButton button2 = new JButton("Dodaj");
JTextField text = new JTextField(23);
JTextArea textArea1 = new JTextArea(10,30);
thePanel.add(button1);
thePanel.add(text);
thePanel.add(button2);
thePanel.add(textArea1);
this.add(thePanel);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
String directory = fileChooser.getCurrentDirectory().toString();
text.append(directory); // doesn't work
}
}
});
this.setVisible(true);
}
private static void createFileChooser(final JFrame frame) {
String filename = File.separator+"tmp";
JFileChooser fileChooser = new JFileChooser(new File(filename));
// pop up an "Open File" file chooser dialog
fileChooser.showOpenDialog(frame);
System.out.println("File to open: " + fileChooser.getSelectedFile());
// pop up an "Save File" file chooser dialog
fileChooser.showSaveDialog(frame);
System.out.println("File to save: " + fileChooser.getSelectedFile());
}
}
However, the append function doesn't work here. Could someone explain why is that? It works unless it isn't in the action listener. My errors are:
Cannot refer to a non-final variable text inside an inner class defined in a different method
The method append(String) is undefined for the type JTextField
I changed to text.append(directory); text.setText(directory); and modified JTextfield to be final and it worked.
Use text.setText(directory) instead of text.append(directory).
The append() method is for JTextArea, JTextField doesn't have it.
And you have to declare JTextField text as final JTextField text.
This question already has answers here:
Select an area to capture using the mouse
(2 answers)
Closed 8 years ago.
In my Java code, I am trying to browse an Image from my directory and then am trying to access to that selected image and capture an area (sub Image) from my image. I have some problems that once I select the image, I do not have access to the image (ImageIcon or BufferedImage). Because, I need its information to get a subimage out of it.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class selectWindow extends JFrame{
// In this GUI project we need just one JPanel inside the JFrame
private JPanel imagePanel;
private JPanel buttonPanel;
private JButton selectImage;
private JLabel imageLabel;
File targetFile;
private ImageIcon image;
static BufferedImage targetImg;
private static final String basePath = "C:\\Users\\mroozbahani3\\Desktop";
private static final int baseSizeX = 900-110;
private static final int baseSizeY = 660;
Rectangle captureRect;
File file;
// Now let's make the constructor
public selectWindow(){
// The below code will close the window(JFrame), once we have click on window exit
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//lets define the default size of our window page(main JFrame), where the first value is the x and second one is y;
setSize(900,660);
selectImage = new JButton("Select Image");
selectImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
image = selectButtonActionPerformed(e);
}
});
imagePanel = new JPanel();
imageLabel = new JLabel(image);
imagePanel.add(imageLabel);
// The below part is for JPanel related to the buttons
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints grid = new GridBagConstraints();
grid.insets = new Insets(10,10,10,10);
// Select Buttom
grid.gridx = 0;
grid.gridy = 1;
buttonPanel.add(selectImage,grid);
// We can determine that how much of the space is going to be belonged to adjustPanel
buttonPanel.setPreferredSize(new Dimension(110,660));
setLayout(new BorderLayout());
add(buttonPanel,BorderLayout.WEST);
add(imagePanel,BorderLayout.EAST);
setResizable( false );
}
private ImageIcon selectButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new ImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
targetImg = rescale(ImageIO.read(file));
return new ImageIcon(targetImg);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
return new ImageIcon(targetImg);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSizeX, baseSizeY, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSizeX, baseSizeY, null);
g.dispose();
return resizedImage;
}
public static void main(String[] args) throws AWTException{
JFrame gui = new selectWindow();
gui.setVisible(true);
}
}
You can create a new Image based on your selection rectangle.
See Screen Image for a simple way to do this.
In our aplication we use Metal L&F. We are using a floatable JToolBar; it happens that when doing the drag behavior it appears with the Windows L&F.
May anyone say me how to keep Metal L&F when dragging the JToolBar?
Thanks
P.D. Our JToolBar is within a JPanel container that user BorderLayout Layout Manager.
Maybe I explained badly my question. So I post an example taken from The Java Tutorials to give anyone an idea of what happens to my application.
If you execute the following code the main JFrame appears decorated with Ocean Theme; but when I drag the JToolBar its decorated is not Ocean. What can I do??.
Many thanks in advance
package components;
/*
* ToolBarDemo.java requires the following addditional files:
* images/Back24.gif
* images/Forward24.gif
* images/Up24.gif
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = "images/"
+ imageName
+ ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ToolBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setsLF();
createAndShowGUI();
}
});
}
/**
*
*/
private static void setsLF() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log (java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
return;
}
}
Looks like nowadays the toplevel container of the ripped of toolBar is of type JDialog, so you have the set the lafDecoration for that as well:
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
JDialog.setDefaultLookAndFeelDecorated(true);
Works for jdk7 and vista, didn't test other environments.
I made a small project as you described:
public class LafTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel(new BorderLayout());
JToolBar toolbar = new JToolBar();
toolbar.add(new JButton("button1"));
toolbar.add(new JButton("button2"));
panel.add(toolbar, BorderLayout.PAGE_START);
frame.add(panel);
frame.setVisible(true);
}
}
Works fine for me, all the time the JToolBar has Metal-LAF.
(OS: Windows 7 x64, java version "1.7.0_09")
Please compare your code with this snippet. Propably you used the UIManager-class somewhere. If you still cannot fix this issue, you should post some of the used code and maybe some more details about your OS and the used Java version.