0

我想从我的文本字段中获取数据并将其设置为 int h。并改变了我绘制的矩形的大小,但我不确定如何从文本字段中获取数据,我厌倦了在 actionperfomred 中使用 e.getsource 但它找不到我的文本字段。我的代码如下:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.sql.*;
import java.lang.Object;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 * This class demonstrates how to load an Image from an external file
 */
public class test extends Component {

    int x=77, y=441, w=23, h=10;

    BufferedImage img =
  new BufferedImage(100, 50,
                    BufferedImage.TYPE_INT_ARGB);    
   // BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
           // g.fillRect(10,10,10,10);
    }

    public test() {
       try {
           img = ImageIO.read(new File("sales-goal.png"));
       } catch (IOException e) {}


       Graphics2D g = img.createGraphics();
       Color myColor = Color.decode("#32004b");
       g.setColor(myColor);
       g.fillRect(x,y,w,h);
                //77,441,23,10
    }

    public Dimension getPreferredSize() {
        if (img == null) {
             return new Dimension(100,100);
        } else {
           //return new Dimension(img.getWidth(null), img.getHeight(null));
            return new Dimension(300,600);
       }
    }

    public static void main(String[] args) {

        JFrame f = new JFrame("Load Image Sample");
        JTextField textField=new JTextField();
        f.add(textField);
        textField.setBounds(10,10,40,30);
        textField.setVisible(true);

        f.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });

        f.add(new test());
        f.pack();
        f.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
               // if (e.getSource() == textField) {}

    }
}
4

2 回答 2

1

该变量textField是本地的main。如果要从 访问它actionPerformed,则需要将其更改为实例变量。

于 2012-04-13T17:34:17.733 回答
1

是的。我同意@jpm。您需要将其声明为实例变量。请执行下列操作:-

  public class test extends Component {
       //Declare the variable here.
       private static JTextField textfield;

    public static void main(String[] args) {
       //Whenever you use the textfield use like this. Remove the keyword 'JTextField'.
       textfield = new JTextField();
  }
  }
于 2012-04-13T18:40:40.960 回答