你如何从JTextField中读取一个整数并在更多方法中使用它?

时间:2016-10-11 16:15:38

标签: java swing numbers jtextfield

我遇到以下问题: 我需要从我的JTextField中读取一个整数,并在绘图方法(paintComponent)中再次使用它。有了这个整数,我需要设置方块的大小。我已经在文本字段中添加了一个监听器,并为它创建了一个类,以便将值作为整数获取,然后重新绘制。但广场保持相同的大小。

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*;  

class MouseDemoOld extends JPanel implements MouseListener 
  {
  int x, y; // location of mouse
  int sx, sy; // size of shape 
 JFrame frame;
 JTextField tf;

 void buildIt() 
 {     
   frame = new JFrame("MouseDemo");
   tf = new JTextField("100");
   frame.add(this);
   frame.add(tf, BorderLayout.SOUTH);
   this.x = 150;
   this.y = 150;
   this.sx = 10;
   this.sy = sx;

    HandlerClass handler = new HandlerClass();
    tf.addActionListener(handler);

    this.addMouseListener(this); // MouseDemo is its own MouseListener!  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setLocation(200, 200);
    frame.setVisible(true);
    }

  public void paintComponent(Graphics g) 
  {
    super.paintComponent(g);
    g.setColor( Color.blue );
    g.fillRect(x - sx/2, y - sy/2, sx, sy);
  }    

  // the method from MouseListener we're interested in this time
  public void mousePressed( MouseEvent e) 
  {
    // add code to update x and y 
    x = e.getX();
    y = e.getY();
    repaint();
  }   

  public void mouseReleased( MouseEvent e) { }
  public void mouseClicked( MouseEvent e) { }
  public void mouseEntered( MouseEvent e) { }
  public void mouseExited( MouseEvent e) { }

  private class HandlerClass implements ActionListener
  {
    public void actionPerformed(ActionEvent event)
    {
      if(event.getSource()==tf)
      {
        int text = Integer.parseInt(tf.getText());
        int sx = text;
        int sy = text;
        repaint();
      }
    }
  }

  public static void main(String[] args) 
  {
    new MouseDemoOld().buildIt(); 
  }
}  

1 个答案:

答案 0 :(得分:1)

请勿在{{1​​}}中重新定义sxsy。由于HandlerClass是一个内部类,因此它可以访问外部类的HandlerClasssx字段。因此,只需从sy中的两个变量中删除int关键字即可。此外,如果在文本字段中输入非整数,您希望在调用HandlerClass时捕获NumberFormatException