Rabu, 10 November 2010

membuat sebuah GUI sederhana dengan java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/* @author Dion Dirza
 */
class swingFrame extends JFrame {

    private int lebar = 320;
    private int tinggi = 125;

    public swingFrame() {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setTitle("Swing Components");
        setSize(lebar, tinggi);
        setLocation((screen.width - this.lebar) / 2, (screen.height - this.tinggi) / 2);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        swingPanel panel = new swingPanel();
        Container cont = new Container();
        cont = getContentPane();
        cont.setLayout(null);
        panel.setBounds(35, 20, 250, 50);
        cont.add(panel);
    }
}

class swingPanel extends JPanel {

    private JButton fakbutton = new JButton("Proses");
    private JButton reset = new JButton("Reset");
    private JTextField angka1 = new JTextField("");
    private JTextField hasil = new JTextField("");

    public swingPanel() {
        fakbutton.addActionListener(new fungsiAction());
        reset.addActionListener(new fungsiAction());
        hasil.setEditable(false);

        setLayout(new GridLayout(2, 2, 5, 5));
        add(angka1);
        add(fakbutton);
        add(hasil);
        add(reset);
    }

    int faktorial(int x) {
        if (x == 1) return 1;
        else return x  * faktorial(x - 1);
    }

    private class fungsiAction implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            try {
                if (ae.getActionCommand().equals("Proses")) {
                    int var = Integer.parseInt(angka1.getText());
                    hasil.setText(Integer.toString(faktorial(var)));
                    fakbutton.setEnabled(false);
                } else {
                    angka1.setText("");
                    hasil.setText("");
                    fakbutton.setEnabled(true);
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "angka yang anda masukan salah",
                            "ERROR", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

public class Swing {

    public static void main(String[] args) {
        swingFrame frame = new swingFrame();
        frame.setVisible(true);
    }
}

Tidak ada komentar:

Posting Komentar