- BASICS
- Classes
- Objects
- Arrays
- Variables
- Loops
- Numbers
- Strings
- Exceptions
- Regexp
- OOP
- Inheritance
- Polymorphism
- Static Keyword
- Abstract Keyword
- Interfaces
- Constructors
- Packages
- Nested Classes
- Final Keyword
- SWING
- Frame
- Panel
- Listener
- Combo Box
- Label
-
Image
- Menu
- Table
- Layout
- Drawing
- Timer
- Designer
- COLLECTIONS
- Lists
- Comparable
- Sets
- Maps
- Generics
- Properties
- Streams
- Json
- COMPILER
- Sublime Text
- Apache Ant
- I/O
- Streams IO
- Socket
- Watching Files
- Logger
- Clipboard
- Encrypt
- JAVAFX
- Openjfx
- Scene Builder
- First App
- Jar Archive
- On Action
- Change Listener
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: 531 days ago