Chào mừng các bạn đến với blog CarrY4U. Trong bài hướng dẫn này mình sẽ hướng dẫn các bạn cách tạo ra chương trình máy tính bỏ túi đơn giản bằng Java Swing.
Đây là chương trình của mình

- Đầu tiên chúng ta tạo một class có tên Calculator.
- Tiếp đến là tạo các nút bấm cho máy tính của chúng ta
private JButton btn;
private JPanel panelcalculator;
private String btnName[] = { "^_^", "C", "Del" , "+",
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"neg", "0", ".", "="};
/*Khởi tạo jbutton*/
private JButton myButton(String btnname)
{
btn = new JButton(btnname);
btn.setBackground(Color.white);
btn.setForeground(Color.red);
btn.addActionListener(this);
return btn;
}
/*Add các jbutton vào panel*/
public JPanel createButtonofCalculator()
{
panelcalculator = new JPanel(new GridLayout(5, 4));
for(int i=0;i < btnName.length;i++)
{
panelcalculator.add(myButton(btnName[i]));
}
panelcalculator.setBackground(Color.white);
return panelcalculator;
}
Ở đây thay vì chúng ta phải khởi tạo 20 nút tương ứng với 20 button. Thì chúng ta sẽ dùng mảng các chuỗi, mỗi nút sẽ tương ứng với một chuỗi,chúng ta sẽ sử dụng vòng để đưa giá trị của chuỗi theo thứ tự vào trong button vừa khởi tạo.
- Tiếp theo sẽ khởi tạo jtextArea sẽ là phần hiển thị thông tin nhập xuất trên máy tính của chúng ta
private JPanel panelOUTPUT;
private JTextArea textarea;
/* Khởi tạo jtextarea */
private JPanel createTextArea() {
panelOUTPUT = new JPanel(new GridLayout(1, 1));
textarea = new JTextArea(3, 3);
textarea.setBackground(Color.WHITE);
panelOUTPUT.add(textarea);
textarea.setEditable(false);
return panelOUTPUT;
}- Tiếp đến là phần xử lý các phép toán trên máy tính bỏ túi của chúng ta
Đoạn code bên dưới mình đã comment khá kỷ các bạn có thể xem qua
private double a =0;
private int casenumber = 0;
private double result = 0;
private double b=0;
public void actionPerformed(ActionEvent e) {
// Ở đây chúng ta sẽ bắt sự kiến cho từng nút
if(e.getActionCommand() == "1")
textarea.append("1");
if(e.getActionCommand()=="2")
textarea.append("2");
if(e.getActionCommand()=="3")
textarea.append("3");
if(e.getActionCommand()=="4")
textarea.append("4");
if(e.getActionCommand()=="5")
textarea.append("5");
if(e.getActionCommand()=="6")
textarea.append("6");
if(e.getActionCommand()=="7")
textarea.append("7");
if(e.getActionCommand()=="8")
textarea.append("8");
if(e.getActionCommand()=="9")
textarea.append("9");
if(e.getActionCommand()=="0")
textarea.append("0");
if(e.getActionCommand()==".")
textarea.append(".");
if(e.getActionCommand()=="neg") //Dấu âm (negative)
textarea.append("-");
/*Khi bắt sự kiến các toán tử chúng ta sẽ gán biến casenumber để thực hiện câu
lệnh switch case
*/
if(e.getActionCommand()=="+")
{
a = Double.parseDouble(textarea.getText());
casenumber= 1;
textarea.setText("");
}
if(e.getActionCommand()=="-")
{
a = Double.parseDouble(textarea.getText());
casenumber= 2;
textarea.setText("");
}
if(e.getActionCommand()=="*")
{
a = Double.parseDouble(textarea.getText());
casenumber= 3;
textarea.setText("");
}
if(e.getActionCommand()=="/")
{
a = Double.parseDouble(textarea.getText());
casenumber= 4;
textarea.setText("");
}
if(e.getActionCommand()=="=")
{
b=Double.parseDouble(textarea.getText());
switch(casenumber)
{
case 1: result = a+b;
break;
case 2: result=a-b;
break;
case 3: result=a*b;
break;
case 4: result=a/b;
break;
default: result=0;
}
textarea.setText(new Double(result).toString());
}
/*Ý tưởng ở đây chúng ta sẽ getText ở textArea sau đó xóa toàn bộ
Tiếp đến duyệt đoạn chuỗi vừa rồi đồng thời lùi về một ký tự
Và cuối cùng setText cho textArea
*/
if(e.getActionCommand()=="Del")
{
String s=textarea.getText();
textarea.setText("");
for(int i=0; < s.length()-1;i++) {
textarea.setText(textarea.getText()+s.charAt(i));
}
//Xóa hết
if(e.getActionCommand()=="C")
textarea.setText("");
}
}
Q: Tại sao không sử dụng setText mà lại dùng append(hàm nối chuỗi trong jtextarea)
A: Bởi vì nếu sử dụng setText nếu nhấn một số mới vd: muốn nhấn số 15 thì phải ấn 2 nút 1 và 5 thì ở đây hàm setText khi ta ấn nút tiếp theo nó sẽ xóa toàn bộ giá trị bạn đầu và set lại giá trị mới. Và những gì hiển thị trên jtextArea của chúng ta lúc này là 5 thay vì 15.
- Đây là full source code của chương trình
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class Calculator extends JFrame implements ActionListener{
private double b;
private JPanel panelcalculator,mainPanel,panelOUTPUT;
private JTextArea textarea;
private String btnName[] = { "^_^", "C", "Del" , "+",
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"neg", "0", ".", "="};
private JButton btn;
private double a =0;
private int casenumber = 0;
private double result = 0;
public Calculator() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(240,330);
setLocationRelativeTo(null);
setResizable(false);
add(createmainFrame());
}
/*Hàm tạo panel chính*/
public JPanel createmainFrame()
{
setTitle("Calculator");
mainPanel = new JPanel(new BorderLayout(4,5));
mainPanel.add(createButtonofCalculator(),BorderLayout.CENTER);
mainPanel.add(createTextArea(),BorderLayout.NORTH);
mainPanel.setBackground(Color.white);
return mainPanel;
}
/*Khởi tạo jbutton*/
private JButton myButton(String btnname)
{
btn = new JButton(btnname);
btn.setBackground(Color.white);
btn.setForeground(Color.red);
btn.addActionListener(this);
return btn;
}
/*Add các jbutton vào panel*/
public JPanel createButtonofCalculator()
{
panelcalculator = new JPanel(new GridLayout(5, 4));
for(int i=0;i<btnName.length;i++)
{
panelcalculator.add(myButton(btnName[i]));
}
panelcalculator.setBackground(Color.white);
return panelcalculator;
}
/* Khởi tạo jtextarea */
private JPanel createTextArea() {
panelOUTPUT = new JPanel(new GridLayout(1, 1));
textarea = new JTextArea(3, 3);
textarea.setBackground(Color.WHITE);
textarea.setForeground(Color.DARK_GRAY);
panelOUTPUT.add(textarea);
textarea.setEditable(false);
return panelOUTPUT;
}
public void actionPerformed(ActionEvent e) {
// Ở đây chúng ta sẽ bắt sự kiến cho từng nút
if(e.getActionCommand() == "1")
textarea.append("1");
if(e.getActionCommand()=="2")
textarea.append("2");
if(e.getActionCommand()=="3")
textarea.append("3");
if(e.getActionCommand()=="4")
textarea.append("4");
if(e.getActionCommand()=="5")
textarea.append("5");
if(e.getActionCommand()=="6")
textarea.append("6");
if(e.getActionCommand()=="7")
textarea.append("7");
if(e.getActionCommand()=="8")
textarea.append("8");
if(e.getActionCommand()=="9")
textarea.append("9");
if(e.getActionCommand()=="0")
textarea.append("0");
if(e.getActionCommand()==".")
textarea.append(".");
if(e.getActionCommand()=="neg")//Dấu âm (negative)
textarea.append("-");
if(e.getActionCommand()=="+")
{
a = Double.parseDouble(textarea.getText());
casenumber= 1;
textarea.setText("");
}
if(e.getActionCommand()=="-")
{
a = Double.parseDouble(textarea.getText());
casenumber= 2;
textarea.setText("");
}
if(e.getActionCommand()=="*")
{
a = Double.parseDouble(textarea.getText());
casenumber= 3;
textarea.setText("");
}
if(e.getActionCommand()=="/")
{
a = Double.parseDouble(textarea.getText());
casenumber= 4;
textarea.setText("");
}
if(e.getActionCommand()=="=")
{
b=Double.parseDouble(textarea.getText());
switch(casenumber)
{
case 1: result = a+b;
break;
case 2: result=a-b;
break;
case 3: result=a*b;
break;
case 4: result=a/b;
break;
default: result=0;
}
textarea.setText(new Double(result).toString());
}
if(e.getActionCommand()=="Del")
{
String s=textarea.getText();
textarea.setText("");
for(int i=0;i<s.length()-1;i++){
textarea.setText(textarea.getText()+s.charAt(i));
}
if(e.getActionCommand()=="C")
textarea.setText("");
}
public static void main(String[] args) {
new Calculator().setVisible(true);
}
}Cảm ơn các bạn đã theo dõi bài viết. Nếu có bất kỳ thắc mắc nào hãy để lại comment phía dưới
By N-13

run file bị lỗi ở hàm main ạ. em cảm ơn