Contoh program sederhana yang menampilkan form login di dalam JFrame. Inputan username berupa JTextField dan inputan password berupa JPasswordField serta tombol dibuat dengan JButton. Form sederhana ini juga mendemonstrasikan adanya Listener berupa ActionListener.
01.
import
java.awt.*;
02.
import
java.awt.event.*;
03.
import
javax.swing.*;
04.
05.
public
class
SimpleLogin
extends
JFrame
implements
ActionListener {
06.
private
JLabel label1, label2;
07.
private
JTextField txtUser;
08.
private
JPasswordField pwdPass;
09.
private
JButton btnLogin, btnExit;
10.
11.
public
SimpleLogin() {
12.
super
(
"Login here..."
);
13.
14.
Container container = getContentPane();
15.
container.setLayout(
new
FlowLayout());
16.
17.
label1 =
new
JLabel (
"Username : "
);
18.
label2 =
new
JLabel (
"Password : "
);
19.
20.
txtUser =
new
JTextField (
20
);
21.
txtUser.setToolTipText(
"Input Username"
);
22.
pwdPass =
new
JPasswordField(
20
);
23.
24.
btnLogin =
new
JButton (
"Login"
);
25.
btnLogin.addActionListener(
this
);
26.
btnExit =
new
JButton (
"Exit"
);
27.
btnExit.addActionListener(
this
);
28.
29.
container.add(label1);
30.
container.add(txtUser);
31.
container.add(label2);
32.
container.add(pwdPass);
33.
container.add(btnLogin);
34.
container.add(btnExit);
35.
36.
setSize (
300
,
200
);
37.
setVisible (
true
);
38.
}
39.
40.
public
static
void
main (String args[]) {
41.
SimpleLogin test =
new
SimpleLogin();
42.
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
43.
}
44.
45.
private
String user =
""
, pass =
""
;
46.
public
void
actionPerformed (ActionEvent e) {
47.
if
(e.getSource() == btnLogin) {
48.
user = txtUser.getText();
49.
pass = pwdPass.getText();
50.
if
(user.equals(
"achmatim"
) && pass.equals(
"otim"
)) {
51.
JOptionPane.showMessageDialog(
null
,
"Login successfull"
);
52.
}
else
{
53.
JOptionPane.showMessageDialog(
null
,
"Username and password dosn't match!"
);
54.
txtUser.setText(
""
);
55.
pwdPass.setText(
""
);
56.
txtUser.requestFocus(
true
);
57.
}
58.
}
else
if
(e.getSource() == btnExit){
59.
JOptionPane.showMessageDialog(
null
,
"Thanks to try my program. See you.."
);
60.
System.exit(
0
);
61.
}
62.
}
63.
}
0 komentar:
Posting Komentar
Jangan lupa tinggalkan komentar