Java Swing - why cant I add image to Jpanel? - java

I dont know why I cant add image to my JPanel
i use code:
class PanelGlowny extends JPanel {
private JLabel adam;
private JButton henryk;
PanelGlowny(){
this.setLayout(new BorderLayout());
ImageIcon imageurl = new ImageIcon("logo.jpg");
//Image img = imageurl.getImage();
adam = new JLabel(imageurl);
add(adam, BorderLayout.NORTH);
henryk = new JButton();
add(henryk, BorderLayout.CENTER);
}
}
Image is in the same folder as class, but if I use url to image it also do not add anything.
This code adding button, but do not add image :(
The problem is probably with my JDE, or Sandbox or sth like this, because code should be fine.

Try this:
imageurl = new ImageIcon(getClass().getResource("logo.jpg"));
Check How to Use Icons tutorial.
EDIT: loading remote image
Try that to load your image from web:
public static void main(String args[]) {
try {
JOptionPane.showMessageDialog(null, "", "",
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(new URL("http://marinerczarter.pl/wp-content/themes/twentyten/images/headers/path.jpg")));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}

Related

Not work in auto generated but work when I manual coding?

This is so frustrated. The code only work on manual generated but not work in auto generate ???
There is an image in project "Bird.png".
public ComboBox() {
initComponents();
try {
image = ImageIO.read(new File("Bird.png"));
lblShow = new JLabel(new ImageIcon(image.getScaledInstance(300, 300, Image.SCALE_SMOOTH)));
} catch (Exception e) {
}
}
This is my manual generate code :
public MainFrame(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,400);
//create new panel and add panel to frame
JPanel pnlImg=new JPanel();
add(pnlImg);
//create new label for showing image
JLabel lblShowImg;
BufferedImage image = null;
try {
image = ImageIO.read(new File("1.jpg"));
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon ii=new ImageIcon(image.getScaledInstance(300,300,Image.SCALE_SMOOTH));
lblShowImg=new JLabel(ii);
/*add label to panel */
pnlImg.add(lblShowImg);
/* show frame*/
setVisible(true);
}
Why is this not working?
public ComboBox() {
initComponents();
try {
image = ImageIO.read(new File("Bird.png"));
lblShow = new JLabel(new ImageIcon(image.getScaledInstance(300, 300, Image.SCALE_SMOOTH)));
} catch (Exception e) {
}
}
Likely due to your not taking layout managers into account, but the truth is, as written it is impossible to say
You never show where you add the JLabel to any container
You don't indicate what layout manager the container is using
You haven't posted a valid mcve.
To possibly solve this --
allow NetBeans to generate a JPanel
Add your JLabel to your own JPanel, one whose layout you control.
Add both to a JFrame (respecting its contentPane's layout) that you display.

Java program Class Menu

I have to use the function of this class in another class in action_performed. This code is giving me error.
public class Menu {
public void Menu()
{
try {
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));\\to get image
Image img1 = ImageIO.read(getClass().getResource("Image2.jpg"));
Image img2 = ImageIO.read(getClass().getResource("Image3.png"));
Image img3 = ImageIO.read(getClass().getResource("Image4.jpg"));
Image img4= ImageIO.read(getClass().getResource("Image5.jpg"));
Image img5= ImageIO.read(getClass().getResource("Image6.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
f1.setVisible(true);
JPanel P1=new JPanel();
P1.setVisible(true);
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
b1.add(P1);
b1.setVisible(true);
P1.add(f1);
} catch (IOException ex) {
}
}
}
Cant add more details and this is all I can tell Just tell me how to solve this problem as quick as possible.
Remove the line:
P1.add(f1);
This will give you a java.lang.IllegalArgumentException because you are trying to add a window to a container. It should work if you remove that line.
However, your code is totally incorrect. You are adding a JFrame to a JPanel and adding the JPanel to the JButton, it should be the opposite way around.
For example, this will work for you:
public void Menu()
{
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
JPanel P1=new JPanel();
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
P1.add(b1);
f1.add(P1);
f1.setVisible(true);
}

Image won't appear in JLabel

I've created GUI for my application using Netbeans' GUI Builder. I am trying to display a JFrame containing a JLabel with an image, and I can't get the Image to display.
My generated code :
private void initComponents() {
//...
jLabel1 = new JLabel(new ImageIcon(myPicture));
}
And my class code:
public class GUIWindow extends javax.swing.JFrame {
BufferedImage myPicture;
/** Creates new form GUIWindow */
public GUIWindow() throws IOException {
myPicture = ImageIO.read(new File("images/logo.png"));
initComponents();
this.add(jLabel1);
}
}
but I still don't see an image ... (path to the image file is fine) its sth like:
my-project :
/build
/dist
/images/logo.png
/nbproject
/src (here I have all my source files)
/build.xml
/manifest.mf
you can use like this
URL imgSmartURL = this.getClass().getResource("your image path");
jLabel1 = new JLabel(new ImageIcon(imgSmartURL), JLabel.CENTER);
I would do something like this instead.
JLabel dice1 = new JLabel();
ImageIcon one = new ImageIcon("dice/1.png");
//set dice1 position
dice1.setLocation(20, 100);
dice1.setSize(115, 115);
dice1.setIcon(one);
gamepanel.add(dice1);
If you are using netbeans you can directly add an image to a jLabel by setting properties. Right click on the jLabel -> properties -> icon -> (if it's external image) import to project(upload your image) -> ok .
It'l be added into your jLabel.
I'd suggest you copy the image in a seperate folder(images).
Then use Toolkit.getDefaultToolkit().getImage("images/A.png");
I believe there's a similar question
private ImageIcon imageIconPrint =
new ImageIcon(getClass().getResource("/image/print.gif"));
create button and add follwing code:
jbtCanada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jlblFlag.setIcon(imageIconCanada);
}
});
this would help i think

Loading animated GIF in JLabel weirdness

I'm trying to load an animated GIF in a JLabel.
While this works:
URL urlsd;
try {
urlsd = new URL("http://pscode.org/media/starzoom-thumb.gif");
ImageIcon imageIcon = new ImageIcon(urlsd);
JLabel progress = new JLabel(imageIcon);
progress.setBounds(5, 20, 66, 66);
contentPane.add(progress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
This, on the other hand, does not, and I don't want to get the GIF from an URL, since I already have the GIF. Result of loading this shows only the first frame of the GIF:
try {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("res/images/progress_indicator.gif")));
JLabel progress = new JLabel(imageIcon);
imageIcon.setImageObserver(progress);
progress.setBounds(5, 20, 66, 66);
contentPane.add(progress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
I guess there must be a reason for this, but I cannot find it.
Thanks!
Alex
You can try loading your GIF file like that:
public class Test extends JPanel {
public Test() {
ImageIcon imageIcon =
new ImageIcon(Test.this.getClass().getResource("starzoom-thumb.gif"));
}
}
Or using Test.class.getResouce() if your context is static.
Below code worked for me, it will show the animation instead of first frame of the image.
public class Test extends JPanel {
public Test() {
ImageIcon yyyyIcon = new ImageIcon(xxx.class.getClassLoader().getResource("yyyy.gif"));
connectionLabel.setIcon(yyyy);
}
}
So there is also a simpler way of doing it. The following line is how I did it.
this.setContentPane(new JLabel(new ImageIcon("Path To Gif File")));

Why slideshow not working in Java using Swing and Awt?

I am doing slideshow of images program in java using timer.
In timer event listner i have added code to chnage image but image is not changing.
Below is the code i have written
class ImagePanel extends JPanel {
private Image backgroundImage;
public ImagePanel(Image backgroundImage) {
super();
this.backgroundImage = backgroundImage;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.backgroundImage, 0, 0, null);
}
}
public class A extends JFrame{
static int counter;
List<String> imagePaths;
int nimgpaths=0;
static A frame = new A();
public static void main(String[] args) {
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getPath();
/* Getting required image */
Image backgroundImage = null;
String pathToTheImage = "C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\civ1.JPG";
try {
backgroundImage = ImageIO.read(new File(pathToTheImage));
} catch (IOException e) {
e.printStackTrace();
}
/* Initializing panel with the our image */
ImagePanel panel = new ImagePanel(backgroundImage);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.timerEvent();
//frame.show();
}
public void timerEvent(){
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Time event occured");
if(counter > nimgpaths)
counter=0;
String imgPath=imagePaths.get(counter);
Image backgroundImage = null;
try {
backgroundImage = ImageIO.read(new File(imgPath));
}catch (Exception e1) {
e1.printStackTrace();
}
/* Initializing panel with the our image */
frame.removeAll();
ImagePanel panel = new ImagePanel(backgroundImage);
panel.repaint();
//panel.setBackground(backgroundImage);
frame.getContentPane().add(panel);
}
});
timer.start();
}
// To get path of images
public void getPath(){
DbOps db=new DbOps();
imagePaths=db.getPath();
nimgpaths=imagePaths.size();
for(Iterator i=imagePaths.iterator();i.hasNext();){
System.out.println((String)i.next());
}
}
}
Why are you using a custom panel and painting?
Your code is simply painting the image at its preferred size. This functionality is available when you use a JLabel. Then when you use the label all you need to do is use:
label.setIcon(....);
when you want to change the image. Read the section from the Swing tutorial on How to Use Icons for more information.
The only reason to create a custom component is if you plan to scale the image or do something fancy like that. If this is the case then you can use something like the Background Panel which supports scaled images as well as a setImage() method so you can change the image dynamically.
A much better design for ImagePanel would let you just replace the image, rather than removing the component. If you do have to replace a visible component, though, you have to call validate() on its container, or the new one isn't going to show up (most of the time, anyway.) I think that's your problem here.
frame.removeAll() is not doing what you would expect - it is removing the components from the frame itself rather than removing the components from the content pane of the frame. Change the code at the end of the timer's action listener to something like this to fix it:
ImagePanel panel = new ImagePanel(backgroundImage);
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
Your concept itself is wrong.
You can refresh the panel like so:
public void refreshPanel(JPanel panel){
panel.removeAll();
panel.invalidate();
panel.validate();
}
Problem:
I see in your code that you are trying to create more than one object of the same panel, which you need to refresh.
It would be better to create one panel object and refresh that object.
ImagePanel panel = new ImagePanel(backgroundImage);
Hope you can understand what I wanted to explain to you.
If you are still confused then let me know.

Categories

Resources