You are on page 1of 2

public class ButtonExample extends JFrame {

/*

Một bài swing bao giờ cũng có ít nhất 5 phần:

PHAN 1: CAC COMPONENTS can co trong bai : vd nhu button , textfield....

PHAN 2: CONSTRUCTOR : chung ta se goi cac ham thao tac voi componets trong constructor

PHAN 3: HAM THAO TAC VOI COMPONETS: cac ham toi thieu phai co:
+ setSize

+ setLocation

+ setDefaultCloseOperation();

PHAN 4: Co the co ham SETLAYOUT

PHAN 5: ham MAIN: + setVisible

*/

// PHAN 1: KHAI BAO CAC COMPONENTS CO BAN


private JButton quitButton;
private JButton jbtOK;

private JTextField jtxtUser;


private JPasswordField jtxtPass;
private JLabel jlUser;
private JLabel jlPass;

// PHAN 2: CONSTRUCTOR
public ButtonExample() throws HeadlessException {
prepareGUI();

// PHAN 3: HAM THAO TAC


private void prepareGUI() {
quitButton = new JButton("Quit"); // initialize quit button
quitButton.setToolTipText("Nhan vao day de tat");
quitButton.setMnemonic(KeyEvent.VK_A);
jbtOK = new JButton("Login");

jtxtUser = new JTextField("Enter your account here");


jtxtPass = new JPasswordField("Enter your password here");

jlUser = new JLabel("User");


jlPass = new JLabel("Password");

// handle the action to the quitbutton


quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});

setLayout(quitButton);
setTitle("Quit Button");
this.pack();
this.setSize(500, 400);
this.setLocation(50, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// PHAN 4: HAM SETLAYOUT


public void setLayout(JComponent... arg) {
Container pane = getContentPane(); // tao 1 cai pane ben trong frame
GroupLayout gl = new GroupLayout(pane); // tao 1 grouplayout roi nem cai pane vao ben trong do
pane.setLayout(gl); // sau do ta set layout cho pane do la group layout

gl.setAutoCreateContainerGaps(true); // automatically creating proper gaps between the components

gl.setHorizontalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jlUser).addComponent(jlPass))
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.TRAILING).addComponent(jtxtUser).addComponent(quitButton))

);

gl.setVerticalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jlUser).addComponent(jtxtUser))
.addGroup(gl.createParallelGroup(GroupLayout.Alignment.BASELINE)).addComponent(jlPass).addComponent(quitButton)
);

// PHAN 5: MAIN
public static void main(String[] args) {
ButtonExample demo = new ButtonExample();
demo.setVisible(true);
}

}
1. Label
2. Button
3. Message dialog
4.

You might also like