Image
Put images/ on project root, on the same level with build/ and src/.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class App extends JFrame {
public static void main(String[] args) {
App frame = new App();
frame.setBounds(200, 200, 300, 300);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); // not BorderLayout !
frame.setVisible(true);
}
public App() { // Look Here
try {
String imageFile = "images/elephant.png";
BufferedImage image = ImageIO.read(new File(imageFile));
JLabel imageLabel = new JLabel(new ImageIcon(image));
add(imageLabel);
} catch (Exception e) {}
}
}
Image Button
Use setIcon() to add an image to a button. Also you can change the cursor using setCursor().
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class App extends JFrame {
public static void main(String[] args) {
App frame = new App();
frame.setBounds(200, 200, 300, 300);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
public App() {
add(new JButton() {{ // Look Here
setIcon(new ImageIcon("images/elephant.png"));
setBorderPainted(false);
setContentAreaFilled(false);
setFocusPainted(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
}});
}
}
Last update: 382 days ago