I
want to share how to CODING FOR COMPONENT FOCUS in J2SE. You can use this code
but if you copy this code and paste in your blog/website, please insert this
link of article.
import java.awt.event.*;
import javax.swing.*;
public class FokusKomponen extends JFrame {
private JTextField txtNama, txtAlamat;
private JButton btnOK;
private JButton btnNO;
public FokusKomponen() {
super("FokusKomponen");
JLabel lblNama = new JLabel("Nama");
JLabel lblAlamat = new JLabel("Alamat ");
JPanel pnl = new JPanel();
pnl.setLayout(new GridLayout(10, 2));
txtNama = new JTextField(15);
txtNama.addFocusListener(new FocusListener() {
// Method ini dipanggil ketika komponen mendapat fokus
public void focusGained(FocusEvent e) {
txtNama.setText("");
}
// Method ini dipanggil ketika komponen tidak mendapat fokus
public void focusLost(FocusEvent e) {
txtNama.setText("agus");
}
});
txtAlamat = new JTextField(15);
txtAlamat.addFocusListener(new FocusListener() {
// Method ini dipanggil ketika komponen mendapat fokus
public void focusGained(FocusEvent e) {
txtAlamat.setText("");
}
// Method ini dipanggil ketika komponen tidak mendapat fokus
public void focusLost(FocusEvent e) {
txtAlamat.setText("klaten");
}
});
pnl.add(lblNama);
pnl.add(txtNama);
pnl.add(lblAlamat);
pnl.add(txtAlamat);
JPanel btnPane = new JPanel();
btnOK = new JButton("OK");
btnPane.add(btnOK);
add(pnl, "North");
add(btnPane, "East");
JPanel btnPane1 = new JPanel();
btnNO = new JButton("NO");
btnPane1.add(btnNO);
add(pnl, "West");
add(btnPane1, "South");
// Registrasi listener window
addWindowListener(new WindowAdapter() {
// Pada saat window dibuka, alihkan fokus
// ke text field txtAlamat
public void windowOpened(WindowEvent e){
txtAlamat.requestFocus();
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FokusKomponen();
}
});
}
}
0 komentar:
Posting Komentar