Skip to content

Instantly share code, notes, and snippets.

@n1try n1try/
Last active Jun 8, 2016

What would you like to do?
HelloSwing - SWT 1 Tut 3 Example
import java.awt.*;
import java.awt.image.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.imageio.*;
public class HelloSwing {
/* Depends on two images "House.png" and "Car.png" to be existing in images/ under the project root directory.
Such can be found at */
private static final String[] AVAILABLE_IMAGES = {"House", "Car"};
private static final String IMAGES_BASE_PATH = "images/";
private static final String IMAGE_TYPE = ".png";
private static JLabel imageContainer;
private static JComboBox imageDropdown;
public static void main(String[] args) {
/* Ideally the GUI should run in a separate Thread to prevent it from getting blocked by expensive
business logic operations. Use javax.swing.SwingUtilities.invokeLater(), pass it a new Runnable and override run method. */
JFrame frame = new JFrame("Hello Swing");
frame.setSize(400, 200);
frame.setLayout(new BorderLayout());
imageDropdown = new JComboBox(AVAILABLE_IMAGES);
imageDropdown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
imageContainer = new JLabel();
frame.add(imageDropdown, BorderLayout.PAGE_START);
frame.add(imageContainer, BorderLayout.PAGE_END);
// Don't forget
private static void updateIcon() {
private static ImageIcon loadImageIcon(String name) {
BufferedImage img = null;
// Don't do this - never just ignore an exception
try {
img = File(IMAGES_BASE_PATH + name + IMAGE_TYPE));
} catch (IOException e) {
return new ImageIcon(img);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.