Mikky
Mikky

Reputation: 345

Loading image from file

I copied the image folder from c:\book\ an put it inside the src folder, but picture didn't load on Label p2.add(new JLabel(icon2));or on Button JButton j2=new JButton(icon2);. Everithing is working out accept pictures.I am a begginer , I don`t have idea what is a problem!

import javax.swing.*;
import javax.swing.ImageIcon;

import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import java.awt.*;
public class TestBorderLayout extends JFrame{

private ImageIcon icon = new ImageIcon("image/ca.gif");
private ImageIcon icon2 = new ImageIcon("image.card/1.png");
public TestBorderLayout(){


 Border lineBorder = new LineBorder(Color.BLACK, 2);    

JButton j1=new JButton("Test1");
 j1.setBackground(new Color(200,0,0));
 j1.setForeground(Color.CYAN);

 JButton j2=new JButton(icon2);

 JButton j3=new JButton("Test3");
 j3.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 12));


JPanel p1=new JPanel();
p1.setBorder(new TitledBorder("One Button"));
p1.add(j1);
p1.add(new TextField("250000000"));
JPanel p2=new JPanel();
p2.add(new JLabel(icon2));


p2.setBorder(new TitledBorder("Two Buttons"));
p2.add(j2);

p2.add(j3);

add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.NORTH);


}

public static void main(String[] args){

    TestBorderLayout frame=new TestBorderLayout();
    frame.setTitle("Border");
    frame.setSize(200,300);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

}

Upvotes: 1

Views: 106

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

Instead

new ImageIcon("image/ca.gif");

do

new ImageIcon(getClass().getResource("/image/ca.gif"));

This getResource returns an URL to a resource (in jar packed file, or file on the class path), with that path. You can use relative paths, relative to the package of the class.


Remark:

At the end of the constructor I would do:

setTitle("Border");
setSize(200,300);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();

That pack does the layouting. But your code is okay.

Upvotes: 2

Related Questions