Java文本框如何输入一个数据,就把数据存入到集合中去?
比如先输入12,就把12add到ArrayList中,文本框再append(24),再把24add到ArrayList中,依次下去。...
比如先输入12,就把12 add到ArrayList中,文本框再append(24),再把24add到ArrayList中,依次下去。
展开
3个回答
展开全部
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class DemoSwing extends JFrame implements KeyListener
{
JTextArea area;
ArrayList array;
public DemoSwing(){
area = new JTextArea();
array = new ArrayList();
area.addKeyListener(this);
this.add(area);
this.setBounds(100, 100, 300, 300);
this.setVisible(true);
}
public static void main(String [] args){
DemoSwing ds = new DemoSwing();
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
if(e.getKeyChar() == KeyEvent.VK_ENTER){
String content = area.getText();
String[] arraysString = content.split(" ");
for(int i = 0; i < arraysString.length; i++){
array.add(Integer.parseInt(arraysString[i]));
}
int sum = 0;
for(int i = 0; i < array.size() ; i++){
sum += (Integer)array.get(i);
}
System.out.println("数值的总和是 " + sum);
}
}
@Override
public void keyReleased(KeyEvent e)
{
// TODO Auto-generated method stub
}
}
好了自己手工写的请采纳
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class DemoSwing extends JFrame implements KeyListener
{
JTextArea area;
ArrayList array;
public DemoSwing(){
area = new JTextArea();
array = new ArrayList();
area.addKeyListener(this);
this.add(area);
this.setBounds(100, 100, 300, 300);
this.setVisible(true);
}
public static void main(String [] args){
DemoSwing ds = new DemoSwing();
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
if(e.getKeyChar() == KeyEvent.VK_ENTER){
String content = area.getText();
String[] arraysString = content.split(" ");
for(int i = 0; i < arraysString.length; i++){
array.add(Integer.parseInt(arraysString[i]));
}
int sum = 0;
for(int i = 0; i < array.size() ; i++){
sum += (Integer)array.get(i);
}
System.out.println("数值的总和是 " + sum);
}
}
@Override
public void keyReleased(KeyEvent e)
{
// TODO Auto-generated method stub
}
}
好了自己手工写的请采纳
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询