I am trying to simply draw an image on a jframe by using an Imageicon. However when I run it its just blank. Heres my code...
public final class PICS
{
public static final void main(String... aArgs)
{
JFrame frame = new JFrame("IMAGE");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
}
}
I am very new to everything java including this website, so I apologize if im missing something. Also im using Eclipse, and are there specific formats you can use for images, or is there a limit to size?
I am very new to everything java including this website
Then I would suggest you start by reading tutorials especially the Swing tutorial. Maybe the section on How to Use Icons would be a good place to start. The example code will show you how to use Icons as well as how to structure your program so that the GUI code is executed on the EDT. The tutorial on Concurrency will explain why the EDT is important.
Two things.
First, make setVisible the last call AFTER you have built your frame and it's contents...ie
JFrame frame = new JFrame("IMAGE");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
// Make me last
frame.setVisible(true);
Two, make sure that the image/pic1.jpg exists and is the directory image under the current execution context.
If the image is a embedded resource (lives within the Jar or your application), then you need to supply a URL to the image instead of a String as ImageIcon treats String as a file name...
ImageIcon image = new ImageIcon(PICS.class.getResource("image/pic1.jpg"));
For example.
I would encourage you to use JFrame#pack over JFrame#setSize as it will resize the frame to the preferred size of your content...
I would also encourage you to take the time to read through Code Conventions for the Java Programming Language, Initial Threads.
I would also encourage you to use ImageIO over ImageIcon as it will, at least, throw an Exception if something goes wrong
Updated, testing image path
Try adding this to the constructor of your PICS class. This will, at least, tell you where the image isn't...
try {
ImageIO.read(PICS.class.getResource("image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in resources/image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /resources/image/pic1.jpg");
}
Related
I wrote code that when I click a java swing button then JAVA plays video stream that python client sends to web. (I use vlcj and mjpg-streamer to play video stream on java swing JFrame.)
Unfortunately It takes all of JFrame spaces but I want to make part of JFrame plays video stream such as JPanel or something. I want to know if there are other ways to make JPanel plays video stream. I hope you help me and thank you for reading.
Below is my code that uses JFrame, VLCJ.
SearchIcon2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String number = CCTV.getSelectedItem().toString();
if (number.equals("no. 1")) {
EmbeddedMediaPlayerComponent component = new EmbeddedMediaPlayerComponent();
final JFrame fs = new JFrame("no. 1");
fs.setContentPane(component);
fs.setBounds(100, 100, 850, 518);
fs.setResizable(false);
fs.setLocationRelativeTo(null);
fs.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
component.release();
fs.setVisible(false);
fs.dispose();
}
});
fs.setVisible(true);
component.mediaPlayer().media().play("http://IP:8090/?action=stream"); // sorry it is my ip.
}
}
});
You are adding the component as content pane, so it covers all of JFrame.
You can use the layout manager of JFrame (default is BorderLayout) or add a JPanel as content pane and add other components using layout manager.
// JFrame layout example
final JFrame fs = new JFrame("no. 1");
fs.add(component, BorderLayout.CENTER);
fs.add(newPanel, BorderLayout.SOUTH);
// JPanel example
JPanel panel = new JPanel();
LayoutManager mgr = ...
panel.setLayout(mgr);
panel.add(component); // maybe layout manager specific parameters also
fs.setContentPane(panel);
I am creating a log in application for someones graduation, I need several text fields and a background, I have added the background and now need to add the text fields, the problem is that they won't seem to go on top of each other.
I have tried them each separately and without one another they both work perfectly but i can't get them to stack, I have seen several answers on this site to deal with a similar problem but for this application I need to put several text fields on the background as apposed to just one, here is what I have thus far...
//creates the frame with a title as a parameter
JFrame frame = new JFrame("Sign In Sheet");
//sets the size
frame.setSize(1000, 556);
//makes it so the application stops running when you close it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//puts it in the center of the screen
frame.setLocationRelativeTo(null);
//makes it so you can't resize it
frame.setResizable(false);
//setting the background by looking for the image
try{
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
}catch(IOException e){
//and prints an error message if it's not found
System.out.println("well it didn't work");
}
//adding text fields with names apropriate to function
JTextField name1 = new JTextField();
name1.setPreferredSize(new Dimension(200, 15));
name1.setBackground(Color.WHITE);
frame.add(name1);
//makes frame visible
frame.setVisible(true);
Simply stated the text field won't show up with the background and all the results only offer answers for a single text field
The problem is in this line: frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
In this line you set a JLabel as the content pane of your JFrame. Then, you frame.add(name1); So you are adding a JTextField to a JLabel...Well this does not seem right, right?
The answer would be to create a new JPanel, add the background image to this panel, set the panel as the content pane of the frame and finally add the textfield to the panel/contentpane.
An example:
#SuppressWarnings("serial")
public class FrameWithBackgroundImage extends JFrame {
public FrameWithBackgroundImage() {
super("Sign In Sheet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
try {
Image bgImage = loadBackgroundImage();
JPanel backgroundImagePanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
};
setContentPane(backgroundImagePanel);
} catch (IOException e) {
e.printStackTrace();
}
JTextField textField = new JTextField(10);
add(textField);
}
private Image loadBackgroundImage() throws IOException {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File image = new File(desktop, "img.jpg");
return ImageIO.read(image);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new FrameWithBackgroundImage().setVisible(true);
});
}
}
Preview:
Worth to read question: Simplest way to set image as JPanel background
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);
Okay, this is likely to be flagged as a repeated question, but please hear me out first. I have looked all over the internet and have tried various ways to show an image in a JFrame, but nothing has worked for me. Is there any simple, foolproof! way to show an image in JFrame? Because if it's not foolproof, I'm sure to mess it up :/
You can try this out, I have commented what I have done and where to try and make it understandable and included a bit about resizing from this post. See how you get on :)
public class SO2 {
public static void main(String[] args) {
try {
//Step 1, read in image using javax.ImageIO
BufferedImage img = ImageIO.read(new File("D:/Users/user/Desktop/Tree.jpeg"));
//Optional, if you want to resize image this is an effective way of doing it
Image scaled = img.getScaledInstance(200, 200, Image.SCALE_SMOOTH);
//Step 2 create frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Step 3 add image to Frame
frame.add(new JLabel(new ImageIcon(scaled)));
//Step 4 Pack frame which sizes it around it's contents, then Show
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am having trouble with this simple example code from the book. It is supposed to represent the same image 2 times in one window (north and south labels), one above the other. When I run it, it displays this instead of this (I am sorry for not cutting the images or resizing them) Below is my code. I am running Eclipse Juno on Ubuntu 13.04.
package gui;
import java.awt.BorderLayout;
import javax.swing.*;
public class Gui {
public static void main(String[] args) {
JLabel northLabel = new JLabel ( "North" );
ImageIcon labelIcon = new ImageIcon ("GUItip.gif");
JLabel centerLabel = new JLabel (labelIcon);
JLabel southLabel = new JLabel (labelIcon);
southLabel.setText("South");
JFrame application = new JFrame();
application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
application.add(northLabel, BorderLayout.NORTH);
application.add(centerLabel, BorderLayout.CENTER);
application.add(southLabel, BorderLayout.SOUTH);
application.setSize(300, 300);
application.setVisible(true);
}
}
You need to concentrate on the following statement:
ImageIcon labelIcon = new ImageIcon ("GUItip.gif");
When initiating new ImageIcon.. it searches the provided address in execution folder by default i.e. in this case "GUItip.gif" shall be searched within workspace/user directory.
One solution is to make available GUItip.gif image in you workspace (program execution) folder.
Another solution would be to provide absolute path.. eg.
C:\USER\Workspace\project_name\GUItip.gif
Though a better approach would be to create a specific folder where you save all images used in your project. Create a final static String variable with absolute path to your folder. Now it would be easy for any programmer in that project to know where to look for images.
There are good approaches to use this mapping.. through XML to be loaded in the beginning.. through resourcebundle etc but that is a different topic altogether.
The image probably isn't loading properly. Try using a try/catch block to see if that's the case.
Ex:
Image img;
File f = new File(//image url);
try {
img = ImageIO.read(f);
} catch (IOException e) {
String curr_dir = System.getProperty("user.dir");
throw new IllegalArgumentException("Image could not be found from " + curr_dir);
}
ImageIcon labelIcon = new ImageIcon(img);