I just started learning GUI programming and I'm facing a problem to load image. I wanted to place a JButton on the WEST of BorderLayout, and display the image in the CENTER by clicking on that JButton.
Please refer to this picture:
The code is as shown below. I've been trying for a few hours but still couldn't make it.
public class Testing extends JFrame {
private JButton btn;
private JLabel pict;
private JPanel wpanel,cpanel;
private BufferedImage image;
Testing(){
Container cont = getContentPane();
setLayout(new BorderLayout());
//add button
wpanel = new JPanel();
cpanel = new JPanel();
btn = new JButton("Click me");
wpanel.add(btn);
//Clicking button to load image
//inner class
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try {
loadImage();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
System.out.println("Couldn't load image.");
}
}
});
public void loadImage() throws IOException{
image = ImageIO.read(Testing.class.getResource("/path/.jpg"));
}
public void createAndShowGUI(){
pict = new JLabel();
pict.setIcon(new ImageIcon(image));
cpanel.add(pict);
}
//end of clicking button to load image
cont.add(wpanel,BorderLayout.WEST);
cont.add(cpanel,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JFrame");
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Testing();
}
});
}
}