Java Swing [deutsch] Kurs 7/100 Taschenrechner (3/3)

Thanks! Share it with your friends!

You disliked this video. Thanks for the feedback!



Added by miamigo
138 Views
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Pattern;


public class Taschenrechner extends JFrame implements ActionListener {


private final JTextField jTextField;
Taschenrechner(int width,int height){
setSize(new Dimension(width,height));


//JTextField
jTextField = new JTextField();
jTextField.setFont(new Font("",Font.PLAIN,20));
jTextField.setHorizontalAlignment(JTextField.RIGHT);


JPanel grid = new JPanel();
grid.setLayout(new GridLayout(4,4));


JButton btn1 = new JButton("1");
btn1.addActionListener(this);
JButton btn2 = new JButton("2");
btn2.addActionListener(this);
JButton btn3 = new JButton("3");
btn3.addActionListener(this);
JButton btnplus = new JButton("+");
btnplus.addActionListener(this);
JButton btn4 = new JButton("4");
btn4.addActionListener(this);
JButton btn5 = new JButton("5");
btn5.addActionListener(this);
JButton btn6 = new JButton("6");
btn6.addActionListener(this);
JButton btnminus = new JButton("-");
btnminus.addActionListener(this);
JButton btn7 = new JButton("7");
btn7.addActionListener(this);
JButton btn8 = new JButton("8");
btn8.addActionListener(this);
JButton btn9 = new JButton("9");
btn9.addActionListener(this);
JButton btngeteilt = new JButton("/");
btngeteilt.addActionListener(this);
JButton btndel = new JButton("del");
btndel.addActionListener(this);
JButton btn0 = new JButton("0");
btn0.addActionListener(this);
JButton btngleich = new JButton("=");
btngleich.addActionListener(this);
JButton btnmal = new JButton("*");
btnmal.addActionListener(this);

grid.add(btn1);
grid.add(btn2);
grid.add(btn3);
grid.add(btnplus);
grid.add(btn4);
grid.add(btn5);
grid.add(btn6);
grid.add(btnminus);
grid.add(btn7);
grid.add(btn8);
grid.add(btn9);
grid.add(btndel);
grid.add(btngleich);
grid.add(btn0);
grid.add(btngeteilt);
grid.add(btnmal);


add(jTextField,BorderLayout.NORTH);
add(grid);


setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



}


@Override
public void actionPerformed(ActionEvent e) {


JButton btn = (JButton)e.getSource();


if (Pattern.matches("[\\d]{1}",btn.getText())){
jTextField.setText(jTextField.getText() + btn.getText());
} else if (btn.getText().equals("del") && !jTextField.getText().equals("")){
jTextField.setText(jTextField.getText().substring(0,jTextField.getText().length()-1));
}
}
}
Category
LOFOTEN
Commenting disabled.