【问题标题】:Incrementing value of an integer in JTextAreaJTextArea中整数的递增值
【发布时间】:2015-02-25 07:14:49
【问题描述】:

我在下面的代码中创建了一个 JTextArea 和 Menubar,我在其中添加了 menuItem Inc.

我已经对 "val" = 0 的值进行了编码,因此当代码运行并出现框架时,首先看到的是零。但是我想在按下 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));
   }

  }  
}

【问题讨论】:

  • 看看你的控制台。您应该看到 NullPointerException 的堆栈跟踪。分析堆栈跟踪,并尝试找出什么是 null 以及为什么是 null。提示:实例字段与局部变量。
  • 了解variables

标签: java swing jbutton actionlistener jtextarea


【解决方案1】:

myFrames 构造函数中,将JTextArea area = new JTextArea(20,15); 替换为area = new JTextArea(20,15);

【讨论】:

    【解决方案2】:

    您覆盖了您的 area 变量。

    变化:

    JTextArea area = new JTextArea(20,15);
    

    收件人:

    area = new JTextArea(20,15);
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 2022-11-26
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 2011-09-13
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多