繁体   English   中英

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

[英]How do you read an integer from JTextField and use it in more methods?

我有以下问题:我需要从我的 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(); 
  }
}  

不要在HandlerClass重新定义sxsy 由于HandlerClass是一个内部类,它可以访问外部类的sxsy字段。 因此,只需从HandlerClass两个变量中删除int关键字。 此外,您希望在调用Integer.parseInt时捕获NumberFormatException ,以防在文本字段中输入非整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM