java在JTextArea中递增整数的值
我在下面的代码中创建了一个JTextArea和Menubar,并在其中添加了menuItem Inc
我已经对“val”=0的值进行了编码,因此当代码运行并显示frame时,第一个看到的是零。但当按下Inc按钮时,我想将这个“0”增加到+1。知道吗,当我按下Inc键时,它一直显示“0” 我的代码如下:
public class Menu
{
public static void main(String[] args)
{
myFrame frame = new myFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(300, 500);
frame.setLocation(600,300);
frame.setTitle("My Menu");
}
}
class myFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JTextArea area;
JMenuItem inc;
int val = 0;
public myFrame()
{
JTextArea area = new JTextArea(20,15);
add(new JScrollPane(area), BorderLayout.CENTER);
String aString = Integer.toString(val);
area.setText(String.valueOf(aString));
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Count");
menuBar.add(menu);
setJMenuBar(menuBar);
JMenuItem inc = new JMenuItem("Inc");
menu.add(inc);
inc.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Inc"))
{
int result = val+1;
String aString = Integer.toString(result);
area.setText(String.valueOf(aString));
}
}
}
# 1 楼答案
在
myFrame
的构造函数中,将JTextArea area = new JTextArea(20,15);
替换为area = new JTextArea(20,15);