Images doesn't work in eclipse - java

I already did search on youtube and here and probably it is silly question but I couldn't find how to make it work.
Question is when I add pictures in my eclipse file they look like;
setLayout(new FlowLayout());
image1 = new ImageIcon(getClass().getResource("view.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("view1.jpg"));
label1 = new JLabel(image2);
add(label2); // here my code
Any ideas?

My got a use method to set icon for label, you can refer
private void loadAvartar(JLabel lbl, String path){
try {
BufferedImage image = ImageIO.read(new File(path));
ImageIcon icon = new ImageIcon(image.getScaledInstance(100, 100, 50));
lbl.setIcon(icon);
} catch (IOException | java.lang.NullPointerException e) {
lbl.setText("Failed");
}
}

Related

Trying to add an image to a label but won't work?

I'm trying to add the image "Pic.png" to this JLabel "label1" and display it on the JPanel "panel1" on a JFrame "window1". But it when I hit run it doesn't display my image. Anyone help? (I read about adding it to the source file or something but I'm not really sure what I'm doing because I'm new to Java. Will it not be able to access the picture without the image being in the source?)
public class UIForIshidaQuery {
public static void main(String[] args) {
System.out.println("Running...");
JFrame window1 = new JFrame();
window1.setVisible(true);
window1.setSize(1080, 720);
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = (JPanel) window1.getContentPane();
JLabel label1 = new JLabel();
panel1.setLayout(null);
ImageIcon image = new ImageIcon("C:\\Users\\BC03\\Pictures\\Saved Pictures\\Other\\Pic.png");
label1.setIcon(image);
label1.setBounds(500, 500, 500, 500);
panel1.add(label1);
}
}
The window should be set visible as the last call. Don't use null layouts1. This works.
import java.net.*;
import javax.swing.*;
public class UIForIshidaQuery {
public static String url = "http://i.stack.imgur.com/gJmeJ.png";
public static void main(String[] args) throws MalformedURLException {
System.out.println("Running...");
JFrame window1 = new JFrame();
window1.setSize(1080, 720);
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = (JPanel) window1.getContentPane();
JLabel label1 = new JLabel();
//panel1.setLayout(null);
ImageIcon image = new ImageIcon(new URL(url));
label1.setIcon(image);
//label1.setBounds(500, 500, 500, 500);
panel1.add(label1);
window1.setVisible(true);
}
}
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
If you are using IntelliJ IDEA:
Right click your project root directory and select New > Directory;
Call the new directory 'resources' for example;
Right click the newly made directory and select Mark Directory As > Resources Root;
Add your image file in the directory;
Access your file properly:
CurrentClass.class.getClassLoader().getResource("pic.png").getFile();
The ImageIcon could be initialized like this:
File file = new File(CurrentClass.class.getClassLoader().getResource("pic.png").getFile());
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(image);

Upload image to server from Java

Follow a small Java code to select an image from a folder. What I would like is to know how to upload it to a server, I have always uploaded images from javascript or jquery or php too. Use a AngularJS frameworks and also to upload images Ionic from mobile devices to my server, I am now working directly in Java and have some doubts. On issues of time, I would like to know how is the best way to upload an image, bits or base64? And if they could help me with this conversion would appreciate. I'm new to Java and I'm just practicing. Regards!
My code :
public class UI extends JFrame {
JButton buttonBrowse;
JButton buttonUpload;
JLabel label;
public UI(){
super("Set Picture Into A JLabel Using JFileChooser In Java");
buttonBrowse = new JButton("Browse");
buttonUpload = new JButton("Upload");
buttonBrowse.setBounds(300,300,100,40);
buttonUpload.setBounds(400, 300, 100, 40);
label = new JLabel();
label.setBounds(10,10,670,250);
add(buttonBrowse);
add(buttonUpload);
add(label);
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
//filter the files
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
//if the user click on save in Jfilechooser
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
System.out.println(path);
label.setIcon(ResizeImage(path));
}
//if the user click on save in Jfilechooser
else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("No File Select");
}
}
});
buttonUpload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(700,400);
setVisible(true);
}
// Methode to resize imageIcon with the same size of a Jlabel
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 UI();
}
}

How to edit changable icon scale?

As I know, to scale icon is toward button itself .
Like this
final JButton satu = new JButton((new ImageIcon(((new ImageIcon("images/1.png").getImage().getScaledInstance(50,50,java.awt.Image.SCALE_SMOOTH))))));
But when I modify to be changeable icon
I don't know how to scale it
is somebody know how to fix it ?
This is the code
final ImageIcon iconsatu = new ImageIcon("images/1.png");
final ImageIcon iconSatu = new ImageIcon("images/r1.png");
satu.addActionListener(new ActionListener() {
private boolean flag = true;
public void actionPerformed(ActionEvent e) {
satu.setIcon(flag?iconsatu:iconSatu);
flag=!flag;
}
});
I don't understand the question. You know how to scale an image as you demonstrated in your first line of code.
So why can't you simply create two scaled Icons:
Icon icon1 = new ImageIcon(((new ImageIcon("images/1.png").getImage().getScaledInstance(...))));
Icon icon2 = new ImageIcon(((new ImageIcon("images/2.png").getImage().getScaledInstance(...))));
Although that code is too complicated. You can simplify it by using something like:
BufferedImage image1 = ImageIO.read( new File("images/1.png") );
Icon icon1 = new ImageIcon( image1.getScaledInstance(...) );

null pointer exception error using action listener

I'm getting the error message null pointer exception on the line img.setIcon(bg); in the controller class in my action listener and I'm not sure why. I've commented where the error is highlighted. Any ideas on why?
public class Display {
public ImageIcon bg;
public JLabel img;
public void UI() {
Controller listener = new Controller();
bg = new ImageIcon("prophase.png");
img = new JLabel(bg, JLabel.CENTER);
JFrame gameFrame = new JFrame();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);// !!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
JLabel jl = new JLabel("What stage of mitosis is this?", JLabel.CENTER);
imgPane.add(img);// center
top.add(jl);// top center
top.add(listener.wordListener());// top center
bottom.add(listener.answer);// bottom
panel1.add(imgPane, BorderLayout.CENTER);// background image (center)
panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used
gameFrame.setJMenuBar(menuBar());
gameFrame.setTitle("Mitosis");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(new ImageIcon("logo.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(400, 300);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
}
}
another class:
public class Controller {
Display display = new Display();
private JFrame dialogFrame = new JFrame();
private ImageIcon logo = new ImageIcon("logo.png");
public String word;
public JLabel answer = new JLabel(" ", JLabel.CENTER);
public JTextField wordListener() {
JTextField tf = new JTextField(10);
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JTextField tf = (JTextField) e.getSource();
word = tf.getText();
if (word.equalsIgnoreCase("Prophase")) {
answer.setText("Correct!");
ImageIcon bg = display.bg;
JLabel img = display.img;
bg = new ImageIcon("interphase.png");
img.setIcon(bg);//error
answer.setText(" ");
} else {
answer.setText("Incorrect, try again.");
}
tf.setText("");
}// end actionPerformed method
});
return tf;
}
}
The default constructor of Display doesn't initialize the attribute img, which is then initialized to null by default. The exception is clearly due to the fact that you are trying to use img without initializing it anywhere. You should define a default constructor for Display that does something like this:
public Display(){
UI();
}
Because in UI() you are initializing img.
Also you have to initialize your display before using img, like this:
Display display = new Display();
Please check if the path for your image is correct
bg = new ImageIcon("interphase.png");
If a resource is not found you will get a NullPointerException when you try to use that imageicon somewhere else.
Try something along the lines
getClass().getResource("interphase.png");
prepend the directory name if needed, in order to get to your image in your resources.
Also, make sure you are initialising the variable in the Display class before using it.

ImageLoading in JPanel using JFileChooser

I am trying to load an image into a JPanel using JFileChooser. But when I try to run the program and load a selected image nothing happens in the JPanel. I am attaching the source code snippet here:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileFilter filter = new FileNameExtensionFilter("Image files","jpeg","jpg");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if(result == fileChooser.APPROVE_OPTION){
imgFile = fileChooser.getSelectedFile();//imgFile is File type
try{
myPicture = ImageIO.read(imgFile);//myPicture is BufferedImage
JLabel picLabel = new JLabel(new ImageIcon( myPicture )) ;
imagePanel.add( picLabel );
imagePanel.repaint();
System.out.println("You have selected "+imgFile);
}catch(Exception e){
e.printStackTrace();
}
}
}
Can anyone shed light on this?
The problem is that I have added two panels in my frame.
You might compare what you're doing with this complete example that uses two panels: a file chooser on the left and a display panel on the right.
I think this might help you...
Object selectedItem = jComboBox14.getSelectedItem();
ImageIcon picturetoInsert = new ImageIcon(selectedItem.toString());
JLabel label = new JLabel("", picturetoInsert, JLabel.CENTER);
JPanel panel = new JPanel(new GridLayout(1, 1));
panel.add(label, BorderLayout.CENTER);
jInternalFrame22.getContentPane();
jInternalFrame22.setContentPane(panel);
jInternalFrame22.setVisible(true);
Why don you try with the paint component?
class imagePanel extends JPanel
{
BufferedImage image;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(image != null)
{
g.drawImage(image, 0, 0, this);
}
}
}
There could be a few reasons for this. You could try
imagePanel.invalidate()
before the repaint call to force it to redraw.
Or possibly the label is to small and needs resizing since there may not have been an image before. You could try invoke the
frame.pack();
method to get the frame to recompute its component sizes.
Or you could try force the size of the label (setting its min size) to ensure it has enough space to show the image.

Categories