I'm trying to add a .gif image to a JButton, but can't seem to get the image to load when i run the code. I've included a screenshot. Included is the frame that's created. I'd really appreciate any help that can be provided. Stack is telling me I can't enter images yet, so it created a link for it. I'm also going to enclose the actual code here:
package java21days;
import javax.swing.*;
import java.awt.*;
public class ButtonsIcons extends JFrame {
JButton load, save, subscribe, unsubscribe;
public ButtonsIcons() {
super("Icon Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
//Icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subscribeIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubscribeIcon = new ImageIcon("unsubscribe.gif");
//Buttons
load = new JButton("Load", loadIcon);
save = new JButton("Save", saveIcon);
subscribe = new JButton("Subscribe", subscribeIcon);
unsubscribe = new JButton("Unsubscribe", unsubscribeIcon);
//Buttons To Panel
panel.add(load);
panel.add(save);
panel.add(subscribe);
panel.add(unsubscribe);
//Panel To A Frame
add(panel);
pack();
setVisible(true);
} //end ButtonsIcon Constructor
public static void main(String[] arguments) {
ButtonsIcons ike = new ButtonsIcons();
}
} //end ButtonsIcon Class
enter image description here
The easiest way is.
Label or Jbutton and what ever else supports HTML 3.5
JLabel a = new JLabel("");
add that to your container.
Haven't figured out how to enter code sorry
Related
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);
So I'm new to Java learning some basics from videos on YouTube, I'm learning to make a GUI/Window and at the moment I'm trying to get iamges to be displayed but I'm not sure if code is wrong/old or the images are not in the right spot/location. Here's what I've written up so far. Help would be much appreciated. Please and Thank you.
import java.awt.*;
import javax.swing.*;
public class FirstGUI extends JFrame {
private static Object out;
private JLabel label;
private JButton button;
private JTextField textfield;
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
public FirstGUI() {
setLayout (new FlowLayout());
label = new JLabel("Hi, I'm a label!");
add(label);
textfield = new JTextField(15);
add(textfield);
button = new JButton("Click me!");
add(button);
button = new JButton("No, CLICK ME!!");
add(button);
label = new JLabel("This is the end of the program?");
add(label);
image1 = new ImageIcon(getClass().getResource("Apiary.png"));
label1 = new JLabel(image1);
image2 = new ImageIcon(getClass().getResource("bee.png"));
label2 = new JLabel(image2);
}
public static void main(String[] args) {
FirstGUI gui = new FirstGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//* gui.setSize(400, 400);
gui.setVisible(true);
gui.setTitle("Hello World");
gui.pack();
}
}
What I get in the errors are:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.(Unknown Source)
at FirstGUI.(FirstGUI.java:39)
at FirstGUI.main(FirstGUI.java:50)
First you're not adding the labels to the frame, so even if that executes it won't show the image icons. So don't forget to add the labels to the frame:
add(label1);
add(label2);
Second I tried your code and it worked fine for me, it only printed the error you mentioned when I didn't import the image icon to the package i'm working in.
For this you need to do this:
Right click on your src package-> import-> General -> File System and then click next and select the directory that contains the images, click Ok and then add the images you specified in the code.
Game(){
JFrame frame = new JFrame("Display Image");
JPanel panel = (JPanel)frame.getContentPane();
frame.setSize(1000,625);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
label.setIcon(new ImageIcon("C:/Users/Ragnar/Desktop/GameBoard.png"));
panel.add(label);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
So i have this constructor ,and i want to add some new JLabels with Images,but i want them to be displayed on top of first image which is the image of the first jLabel label.Can anyone guide me how to achieve this please?I tryed to add them as usually but they are displayed behind the label.
If you have a background image and you want to display the JLabel on top of the background image, you can use a JPanel to hold the background image, then add your JLabel.
Usually if you try to let 2 JLabel overlap each other it won't succeed due to the default layout manager used by the container (such as FlowLayout in JPanel or BorderLayout in JFrame).
If you really want to let them over lap, you will have to set the layout as null. But they may introduce new problems as you lose control over the appearance of your components.
Hence, in cases like this I would usually go for custom painting and draw the images you want in any particular order you are interested in.
For example: How to create a background and foreground image which overlaps?
If you are working with eclipse, and you have installed the windowbuilder plugin you can use the graphical editing view.
Within this view use the contextual menu to order the elements.
What worked for me was, when adding the components with the method add(component), adding them in order from front to back. In the following example I add a lot of components to a JFrame, and the last one to be added is the wallpaper, so it stays at the background.
import java.awt.Image;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LogIn extends JFrame implements ActionListener{
public static JFrame operador;`enter code here`
private JLabel logo, foot, mensaje, wallpaper;
private JTextField fldUser;
private JPasswordField fldPass;
private JButton entrar;
private int ancho =400, largo= 530;
public static String user="", pass="", name;
public LogIn() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(ancho,largo);
setResizable(false);
setTitle("Acceso al sitema");
setLocationRelativeTo(null);
setIconImage(getIconImage());
fldUser = new JTextField();
fldUser.setHorizontalAlignment(JTextField.CENTER);
fldUser.setBounds(125,320,150,25);
fldUser.setBackground(new Color(50,50,255));
fldUser.setForeground(Color.WHITE);
fldUser.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldUser);
fldPass = new JPasswordField();
fldPass.setHorizontalAlignment(JTextField.CENTER);
fldPass.setBounds(125,360,150,25);
fldPass.setBackground(new Color(50,50,255));
fldPass.setForeground(Color.WHITE);
fldPass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldPass);
mensaje= new JLabel();
mensaje.setBounds(0,390,ancho,15);
mensaje.setForeground(Color.RED);
mensaje.setHorizontalAlignment(SwingConstants.CENTER);
add(mensaje);
entrar =new JButton("Entrar");
entrar.setBounds(125,410,150,40);
entrar.setForeground(new Color(50,50,255));
//entrar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
entrar.addActionListener(this);
add(entrar);
logo = new JLabel();
logo.setBounds(50,0,300,300);
ImageIcon imgLogo= new ImageIcon("src/images/DS.png");
Icon iconoLogo = new ImageIcon(imgLogo.getImage().getScaledInstance(logo.getWidth(),logo.getHeight(), Image.SCALE_DEFAULT));
logo.setIcon(iconoLogo);
foot = new JLabel("Desarrollado por Gabriel Santos");
foot.setBounds((ancho-200)/2,largo-60,200,30);
//When JLabels overlap, the ones that come to the front are the first to be added to the window.
add(foot);
add(logo);
wallpaper = new JLabel();
wallpaper.setBounds(0,0,window.getWidth(),window.getHeight());
ImageIcon img = new ImageIcon("src/images/wallpaperPrincipal.jpg");
Icon icono = new ImageIcon(img.getImage().getScaledInstance(this.getWidth(),this.getHeight(), Image.SCALE_DEFAULT));
wallpaper.setIcon(icono);
add(wallpaper);
setVisible(true);
}
}
I'm trying to set the components of this application to a set location using setLocation so far i haven't been able to move the components. There is more code but its get calling and setting this code for the most part. any ideas?
import javax.swing.*;
public class HangmanPanel extends JPanel {
private static final long serialVersionUID = -5793357804828609325L;
public HangmanPanel(){
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener();
JLabel tfLable = new JLabel("Please Enter a Letter");
JTextField text = new JTextField(10);
String input = text.getText();
heading.setLocation(50, 20);
tfLable.setLocation(20, 100);
text.setLocation(320, 50);
Button.setLocation(230, 100);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
You should not use setLocation() to layout Swing components, it is much better to use a Layout. Please have a look at these Layout Tutorials.
I am trying to make a very basic game with Java and I am having trouble displaying an image on a JFrame. It has worked in the past for me and now is not, i can't see what I did wrong.
I have tried printing the current working directory and changing where I get my image to match that. It is likely that the problem is not getting the image, since my (filefinder or filereader or something like that) can find it without problems, but I cannot correctly add it (the ImageIcon) to the JLabel, or that to the JFrame.
This is my code...
JFrame frame = new JFrame("no image");
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(image);
frame.add(imagelabel);
The JFrame has been setVisible(true) and pack().
Could someone please help me understand what is wrong.
Your problem lies here:
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(character);
You create an ImageIcon "image" but you create your JLabel with "character".
It should be:
JLabel imagelabel = new JLabel(image);
Try,
ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);
Take a look at Tutorial - How to use Icons
import javax.awt.*;
import java.awt.*;
import java.awt.event*;
//class name image
class image {
image()
//constructor {
Frame f=new Frame("Image");
//Frame
f.setSize(500,500);
f.setVisible(true);
Panel p =new Panel();
//Panel
f.add(p);
p.addLayout(null);
ImageIcon ii=new ImageIcon("set your image path");
//ImageIcon is used to image Display .
Label l =new Label(ii);
p.add(ii);
p.setBounds(set you bounds);
//Like that(20,20,500,40);
}
public static void main(String [] args) {
image obj = new
}
}