-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicJFrameWithImages.java
More file actions
executable file
·68 lines (56 loc) · 1.93 KB
/
BasicJFrameWithImages.java
File metadata and controls
executable file
·68 lines (56 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
// Adding images to labels and buttons
public class BasicJFrameWithImages implements ActionListener{
JFrame frame;
JPanel myPanel;
JButton rollDie;
JLabel dieFace;
public BasicJFrameWithImages () {
frame = new JFrame ("Basic JFrame with Images Example");
frame.setPreferredSize(new Dimension(200, 250));
frame.setLocation(200, 200);
myPanel = new JPanel ();
myPanel.setLayout (new BoxLayout (myPanel, BoxLayout.PAGE_AXIS));
myPanel.setBackground (Color.white);
myPanel.setBorder (BorderFactory.createEmptyBorder (10,10,10,10));
// Setting an image to the label
dieFace = new JLabel (new ImageIcon ("die1.gif"));
dieFace.setAlignmentX (JLabel.CENTER_ALIGNMENT);
//dieFace.setBorder (BorderFactory.createEmptyBorder (0,0,10,10));
// Adding an image to the button
rollDie = new JButton ("Roll");
ImageIcon icon = new ImageIcon ("dice.jpg");
Image img = icon.getImage();
Image newImg = img.getScaledInstance (20,20,java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon (newImg);
rollDie.setIcon (newIcon);
rollDie.setAlignmentX(JButton.CENTER_ALIGNMENT);
rollDie.addActionListener (this);
myPanel.add (dieFace);
myPanel.add (rollDie);
frame.add (myPanel);
frame.pack ();
frame.setVisible (true);
}
public void actionPerformed (ActionEvent event) {
int num = (int) (Math.random() * 6)+1;
if (num == 1)
dieFace.setIcon (new ImageIcon ("die1.gif"));
else if (num == 2)
dieFace.setIcon (new ImageIcon ("die2.gif"));
else if (num == 3)
dieFace.setIcon (new ImageIcon ("die3.gif"));
else if (num == 4)
dieFace.setIcon (new ImageIcon ("die4.gif"));
else if (num == 5)
dieFace.setIcon (new ImageIcon ("die5.gif"));
else
dieFace.setIcon (new ImageIcon ("die6.gif"));
}
public static void main (String [] args){
new BasicJFrameWithImages ();
}
}