I'm new to Java, and I'm trying to make an JFrame, with a JPanel inside it and an image inside a JLabel. Then by adding the JLabel to the JPanel it must work right? However, this is the way it's done on docs.oracle.com...
This is the code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Interface {
private JPanel panel;
private JPanel buttonPane;
private JLabel label;
private JLabel label2;
private JTextField textfield;
private JTextField textfield2;
private JTextField textfield3;
private JTextField textfield4;
private JTextField textfield5;
private JButton button;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
public static void main(String[] args) {
new Interface();
}
public Interface() {
JFrame frame = new JFrame("Vormen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
panel = new JPanel();
buttonPane = new JPanel();
button = new JButton("cirkel");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JLabel label3 = new JLabel(new ImageIcon("images/cirkel.png"));
panel.add(label3);
panel.revalidate();
panel.repaint();
buttonPane.add(button);
buttonPane.add(button2);
buttonPane.add(button3);
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel);
frame.setVisible(true);
}
}
Your application can't find the ""images/cirkel.png". You have few alternatives:
I use absolute path for quick hacks. For anything serious I would chose resources as they are bundled with your application.