Bản quyền thuộc về TITV.vn,
vui lòng không đăng tải lại nội dung từ trang này.
Video giải thích chi tiết
Code chi tiết
package model;
public class CounterModel {
private int value;
public CounterModel() {
this.value=0;
}
/**
* @return the value
*/
public int getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
public void increment() {
this.value++;
}
public void decrement() {
this.value--;
}
public void reset() {
this.value=0;
}
}
package view;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.nio.ByteOrder;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import controller.CounterListener;
import model.CounterModel;
public class CounterView extends JFrame{
private CounterModel counterModel;
private JButton jButton_up;
private JButton jButton_down;
private JLabel jLabel_value;
public CounterView() {
this.counterModel = new CounterModel();
this.init();
this.setVisible(true);
}
public void init() {
this.setTitle("Counter");
this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener ac = new CounterListener(this);
jButton_up = new JButton("UP");
jButton_up.addActionListener(ac);
jButton_down = new JButton("DOWN");
jButton_down.addActionListener(ac);
jLabel_value = new JLabel(this.counterModel.getValue()+"", JLabel.CENTER);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
jPanel.add(jButton_up, BorderLayout.WEST);
jPanel.add(jLabel_value, BorderLayout.CENTER);
jPanel.add(jButton_down, BorderLayout.EAST);
this.setLayout(new BorderLayout());
this.add(jPanel, BorderLayout.CENTER);
}
public void increment() {
this.counterModel.increment();
this.jLabel_value.setText(this.counterModel.getValue()+"");
}
public void decrement() {
this.counterModel.decrement();
this.jLabel_value.setText(this.counterModel.getValue()+"");
}
}
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import view.CounterView;
public class CounterListener implements ActionListener{
private CounterView ctv;
public CounterListener(CounterView ctv) {
this.ctv = ctv;
}
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println("Ban da nhan nut!");
String src = e.getActionCommand();
System.out.println("Ban da nhan nut: "+ src);
if(src.equals("UP")) {
this.ctv.increment();
}else if(src.equals("DOWN")) {
this.ctv.decrement();
}
}
}
package test;
import model.CounterModel;
import view.CounterView;
public class Test {
public static void main(String[] args) {
CounterModel ct = new CounterModel();
ct.increment();
ct.increment();
ct.increment();
System.out.println(ct.getValue());
ct.decrement();
System.out.println(ct.getValue());
CounterView ctv = new CounterView();
}
}
Thầy giảng hay lắm ạ
Trả lờiXóa