import java.awt.*; import java.awt.event.*; // イベント処理用 import javax.swing.*; public class Ex12_2 extends JPanel { JLabel lbl = new JLabel("整数を1つ入力してボタンを押して下さい"); JTextField txt = new JTextField(); JButton btn = new JButton("偶数/奇数を判定"); public Ex12_2() { // コンストラクタ setLayout(null); add(lbl); lbl.setBounds(50, 50, 250, 30); // (50, 50) w250,h30 add(txt); txt.setBounds(50, 100, 250, 30); // (50,100) w250,h30 add(btn); btn.setBounds(50, 150, 250, 30); // (50,150) w250,h30 btn.addActionListener(new ActionListener() { // ボタンが押されたら… public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(txt.getText()); // TextBoxに入力された値を,整数に変換して,変数numに代入 boolean flg = true; // 判定用ブール値 flg に trueを代入しておく if (num % 2 == 0) { // 値numが偶数なら flg = false; // flg に false を代入 } lbl.setText(num + (flg ? "は奇数だよ。" : "は偶数だよ。")); txt.setText(""); } }); } public static void main(String[] args) { JFrame app = new JFrame(); app.add(new Ex12_2()); app.setSize(400, 300); app.setTitle("偶数/奇数 判定マシン"); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true); } }