日期:2014-05-20  浏览次数:20700 次

java中如何将字符一个个显示在文本区上?求各位大侠指点~
各位大侠好,小弟正研究java,属于菜鸟级别,现有一问题想请教:
我想做一个计算器,监听器已经加上,但就是不懂如何将按钮上的字
显示在文本区上,像我们常用的计算器那样,输入一个就显示一个,计算
后将结果显示,求个为大侠指点指点啊~分数伺候着
------解决方案--------------------



<html>
<body>
  <input  id="allSum" value="0"></input>
  <input type="button" value="1" width="60px" id="button1" onclick="one()"></input>
  <input type="button" value="2" width="60px" id="button2"></input>
  <input type="button" value="+" width="60px" id="button3"></input>
  <input type="button" value="=" width="60px" id="button4"></input>
</body>
<script>
function one(){
var one=document.getElementById("button1").value;
var value=document.getElementById("allSum").value;
if(value==0){
  document.getElementById("allSum").value=one ;
}else{
var result=value+one;
document.getElementById("allSum").value=result;
}
alert(one);

}

</script>
</html>


LZ大致就这意思了,就赋值了一下,算法没给弄。
------解决方案--------------------
给每个按钮的button都设置值,之后点击下,先获取下结果文本的值,之后再添加上去,不过这里面要考虑的情况比较多,慢慢做吧!
------解决方案--------------------
因为是个玩具例子,所以请楼主不要在意,大致是这个意思,当然要想完善还需要多个if语句

f()
{
one = new JButton("1");
two = new JButton("2");
t = new JTextField(10);

one.addActionListener(this);
two.addActionListener(this);
t.addActionListener(this);

}
public void actionPerformed(ActionEvent e) 
{
int result = 0;
if(e.getSource() == one)
{
t.setText("1");
}
else if(e.getSource() == two)
{
t.setText("2");
}
else if(e.getSource() == add)
{
result = Integer.parseInt(t.getText()) + result;
}
}

------解决方案--------------------
不好意思,发得不完整
再来一遍

class f extends JFrame implements ActionListener
{
JButton add = new JButton("加");
JButton one, two;
JTextField t;

f()
{
one = new JButton("1");
two = new JButton("2");
t = new JTextField(10);

one.addActionListener(this);
two.addActionListener(this);
t.addActionListener(this);

}
public void actionPerformed(ActionEvent e) 
{
int result = 0;
if(e.getSource() == one)
{
t.setText("1");
}
else if(e.getSource() == two)
{
t.setText("2");
}
else if(e.getSource() == add)
{
result = Integer.parseInt(t.getText()) + result;
}
}
}

------解决方案--------------------
既然监听器已经加上了,那么监听按钮的事件好了,没点击一次按钮,获取到该按钮上的字符,然后再获取文本区的字符(一开始为空),然后使用java基础的字符串拼接将二者拼接上即可。

嘿,你监听器都搞定了,字符串拼接不可能不会啊?
------解决方案--------------------
http://blog.csdn.net/zhaoming262350/article/details/8250807