我目前正在尝试创建一个简单的访问面板,允许用户点击数字,它将显示在上面的textfield
中,但是当点击该按钮时,textfield
正在填充但是以前的号码正在被覆盖!下面显示了我目前的代码。这是btn1
& btn2
我正在关注这一点:
package securitySystem;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
public class accessPanel extends JFrame {
public static void main (String args[]){
accessPanel gui= new accessPanel ();
gui.setSize (360, 400);
gui.setLocationRelativeTo(null);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setTitle("Access Panel");
gui.setLayout(new BorderLayout());
gui.setBackground(Color.BLACK);
}
JButton btn1= new JButton("1");
JButton btn2= new JButton("2");
JButton btn3= new JButton("3");
JButton btn4= new JButton("4");
JButton btn5= new JButton("5");
JButton btn6= new JButton("6");
JButton btn7= new JButton("7");
JButton btn8= new JButton("8");
JButton btn9= new JButton("9");
JButton btn0= new JButton("0");
JTextField pin = new JTextField();
public accessPanel (){
setLayout(null);
pin.setBounds(0,0,340,40);
add(pin);
btn1.setBounds(0,40,100,70);
add(btn1);
btn2.setBounds(120,40,100,70);
add(btn2);
btn3.setBounds(240,40,100,70);
add(btn3);
btn4.setBounds(0,120,100,70);
add(btn4);
btn5.setBounds(120,120,100,70);
add(btn5);
btn6.setBounds(240,120,100,70);
add(btn6);
btn7.setBounds(0,200,100,70);
add(btn7);
btn8.setBounds(120,200,100,70);
add(btn8);
btn9.setBounds(240,200,100,70);
add(btn9);
btn0.setBounds(120,280,100,70);
add(btn0);
}
public void calcButtons()
{
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pin.setText(btn1.getText());
}
});
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pin.setText(btn2.getText());
}
});
}
}
答案 0 :(得分:0)
拥有一个全局字符串,您可以在每次单击按钮时添加数字
public class accessPanel extends JFrame {
String word = "";
...
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
word += btn2.getText();
pin.setText(word);
}
});
}
如果您有clear
按钮,只需在其actionPerformed中将字符串设置为""