How can I not show the open dialog first? - java

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.

Related

Java - How do I get an image to display?

I have spent a really long time trying to find a way to display an image in a Java program (I'm trying to learn how to make a 2D Java game) an nothing that I've tried works. I'm using Eclipse Mars and the latest of everything else. Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("background.bmp");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Please, just tell me how to correct the code so that the image actually displays. Thank you ahead of time.
(P.S. the "background.bmp" file is in the "default package" if that changes anything)
The image with .bmp suffix can't be displayed in your code. Try to modify
ImageIcon image = new ImageIcon("background.bmp");
to
ImageIcon image = new ImageIcon("background.png");
and change the image name to background.png.
However, if you just want to use background.bmp, you need to modify your code like this and background image will be displayed.
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
File imageFile = new File("background.bmp");
Image i = ImageIO.read(imageFile);
ImageIcon image = new ImageIcon(i);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is the effect with new code:
Hope it helps.
BTW, I've put the image at the root directory of the project.
Read the section from the Swing tutorial on How to Use Icons. The examples their show you how to load the images as resources. When you use resources the classpath will be searched to find the file.
//frame.setLayout(null);
//imageLabel.setLocation(0, 0);
//imageLabel.setSize(1000, 750);
Don't use a null layout and attempt to set the size/location of the label. Let the layout manager do its job. The label will be the size of the image.
//frame.setSize(1000, 750);
frame.pack();
Don't use frame.setSize(...). Instead you use frame.pack() then the frame will be the size of the image plus the size of the frame borders and title. Let Swing and its layout managers do the work for you.
As a beginer, I found that is easy to see the picture you draw:
Source code
public class CheckCodeTest {
private int width = 100, height = 50;
private BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
#Test
public void drawGraphicsTest() throws IOException {
Graphics graphics = image.createGraphics();
// draw an orange rectangle
graphics.setColor(Color.orange);
graphics.fillRect(0,0,width,height);
// layout the picture right now!
graphics.drawImage(image,0,0,null);
ImageIO.write(image, "png", new File("checkcode.png"));
}
}
Output
It produce a picture file under your projects content.
output-picture
Then you can see what change after adding draw code in small window, it is more convenient than closing an jump-out Frame / Label window:
output-picture-in-editor

Java - Getting Thumbnail of File and Resizing

I'm trying to get the Thumbnail that is associated to a particular file, and then resize it. I've been testing on Mac, and haven't been able to find a solution that would allow me to achieve this.
Code so far:
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
Version1 of getting the thumbnail has following behaviour:
Can open thumbnails
Very small, scaling not suitable.
Version2 of getting thumbnail has following behaviour:
Doesn't display image, despite finding image (System.out proves this).
Except for pdf, where instead it displays the actual file, as opposed to the
thumbnail
When it does work i.e. pdf, it scales nicely.
I know I can use sun.awt.shell.ShellFolder;, however I am aiming for a cross-platform solution.
Thanks for any help
I looked at some code that I have done in the past and seems this works fine when you use JLabel with and ImageIcon, try this code that resized a large image to 100x100,
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);

How to add an ImageIcon to a JFrame?

I'm trying to add an image to one frame but it seems it does not working. The image created by an ImageIcon from the specified file. The image file is in the seam directory the java file exist.
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class image {
public static void main(String args[])
{
TimeFrame frame = new TimeFrame();
}
}
class TimeFrame extends JFrame
{
//Image icon = Toolkit.getDefaultToolkit().getImage("me.jpg");
ImageIcon icon = new ImageIcon("me.jpg");
JLabel label = new JLabel(icon);
public TimeFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("My Frame");
setSize(500,400);
//this.setIconImage(icon);
add(label,BorderLayout.CENTER);
setVisible(true);
}
}
If your icon is beside the TimeFrame java file, you should use
java.net.URL imgUrl = getClass().getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
or
java.net.URL imgUrl = TimeFrame.class.getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
You are (probably) currently looking for it in your working directory which you can output via
System.out.println(System.getProperty("user.dir"));
Will u try this one?
ImageIcon ImageIcon = new ImageIcon("me.jpg");
Image Image = ImageIcon.getImage();
this.setIconImage(Image);
Simply change the directory to "src/me.jpg"

how to make image resizeable

i try to make imageviewer, the code is below
import javax.swing.*;
import java.awt.event.*;
import java.IO.*;
public class javaImageViewer extends JFrame{
public javaImageViewer(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(200,100);
JButton openButton = new JButton("Open Images");
getContentPane().add(openButton);
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser(".");
int status = chooser.showOpenDialog(javaImageViewer.this);
if(status == JFileChooser.APPROVE_OPTION){
try{
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(chooser.getSelectedFile().toURL()));
frame.add(label);
frame.setSize(500,500);
frame.setVisible(true);
}
catch(Exception e2){
System.out.println("Error"+e2);
}
}
}
});
}
public static void main(String [] args){
javaImageViewer tim = new javaImageViewer();
tim.setVisible(true);
}
}
but when i open image from camera, it always showing over the frame size
i dont know how to make the image follow my frame size ?
in order to place your image with the Full Size, you can try to make your own JPanel, override the paintComponent method, and inside this method use g.DrawImage ,
other solution and maybe easier is set the JPanel dimesion with the same dimesion of you Image and Add this JPanel to a JScrollPane , in this way is going to show a scrollbars to navigate
depends of reall size in pixels
1) put Image / BufferedImage as Icon/ImageIcon to the JLabel, then image will be resiziable up to real size in pixels
2) resize Image by usage of Image#getScaledInstance(int width, int height, int hints)

Problem with loading image in java with FileChooser

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.

Categories

Resources