簡體   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