< 만드려는 실습 내용 >
굴리기! 버튼 누르면 아래 5가지 옵션 중 랜덤으로 3개와 그 수치가 결정되는 프로그램을 만들어보세요.
<슬롯머신>
힘 증가 : + 1 ~ +7
지능 증가 : +1 ~ +7
민첩 증가 : +1 ~ +7
행운 증가 : +1 ~ +7
공격력 증가 : +1 ~ +3
버튼과 관련된 클래스 2개와 main클래스 1개 를 작성 했다.
import java.util.Random;
import javax.swing.JButton;
public class RandomButton extends JButton{
static String[] stat_labels = {"힘","민첩","지능","행운","공격력"};
static int[] max_stats = {7,7,7,7,3};
Random ran;
public RandomButton() {
super("능력치 부여하기");
ran = new Random();
}
void roll() {
int value = ran.nextInt(stat_labels.length);
setText(stat_labels[value] + " + " + (int)(Math.random()*(max_stats[value]) + 1));
}
}
public class RollButton extends JButton{
private ArrayList<RandomButton> ranBtns;
public RollButton() {
setText("옵션 변경");
ranBtns = new ArrayList<>();
RandomButton b1 = new RandomButton();
b1.setLocation(175,40);
b1.setSize(150,30);
RandomButton b2 = new RandomButton();
b2.setLocation(175,90);
b2.setSize(150,30);
RandomButton b3 = new RandomButton();
b3.setLocation(175,140);
b3.setSize(150,30);
b1.setBackground(new Color(0x8a5700));
b2.setBackground(new Color(0x8a5700));
b3.setBackground(new Color(0x8a5700));
b1.setForeground(new Color(0xfffef5));
b2.setForeground(new Color(0xfffef5));
b3.setForeground(new Color(0xfffef5));
b1.setFont(new Font("고딕",Font.BOLD,16));
b2.setFont(new Font("고딕",Font.BOLD,16));
b3.setFont(new Font("고딕",Font.BOLD,16));
ranBtns.add(b1);
ranBtns.add(b2);
ranBtns.add(b3);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(RandomButton btn : ranBtns) {
btn.roll();
}
}//actionPerformed
});
}
public ArrayList<RandomButton> getRanBtns() {
return ranBtns;
}
}
public class Baram extends JFrame{
private ArrayList<RandomButton> ranBtns;
Random ran;
public Baram() {
super("바람의 나라:연");
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(2000,100);
setSize(500,400);
setVisible(true);
getContentPane().setBackground(new Color(0x041e47));
ranBtns = new ArrayList<>();
RollButton btn = new RollButton();
btn.setLocation(170,230);
btn.setBackground(new Color(0xde9631));
btn.setForeground(new Color(0xfffef5));
btn.setFont(new Font("고딕",Font.BOLD,20));
btn.setSize(160,60);
Border border = new LineBorder(Color.black,2);
btn.setBorder(border);
add(btn);
for(RandomButton ranbtn : btn.getRanBtns()){
add(ranbtn);
}
}
public static void main(String[] args) {
new Baram();
}
}