Last active
June 8, 2016 08:42
-
-
Save muety/7907055d200610a2aec4169d741755d4 to your computer and use it in GitHub Desktop.
HelloSwing - SWT 1 Tut 3 Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.image.*; | |
import java.io.File; | |
import java.io.IOException; | |
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 https://www.iconfinder.com/search/?q=house. */ | |
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.setSelectedIndex(0); | |
imageDropdown.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
updateIcon(); | |
} | |
}); | |
imageContainer = new JLabel(); | |
imageContainer.setHorizontalAlignment(JLabel.CENTER); | |
updateIcon(); | |
frame.add(imageDropdown, BorderLayout.PAGE_START); | |
frame.add(imageContainer, BorderLayout.PAGE_END); | |
// Don't forget | |
frame.setVisible(true); | |
} | |
private static void updateIcon() { | |
imageContainer.setIcon(loadImageIcon(AVAILABLE_IMAGES[imageDropdown.getSelectedIndex()])); | |
} | |
private static ImageIcon loadImageIcon(String name) { | |
BufferedImage img = null; | |
// Don't do this - never just ignore an exception | |
try { | |
img = ImageIO.read(new File(IMAGES_BASE_PATH + name + IMAGE_TYPE)); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return new ImageIcon(img); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment