-1

可能重复:
我不确定如何从我的文本字段中获取数据

我在文本字段中输入一个数字并使用该输入来更改一个 int,这将改变一个矩形的大小,我不确定是否有问题,我没有从该文本字段中获取该数据或页面只是没有重新加载在它得到那个数据之后。

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;


public class Test extends JPanel implements ActionListener{

    JTextField textField;
    JFrame f=new JFrame();
    int x=77, y=441, w=23, h=10, entry;
    BufferedImage img=null;

   // BufferedImage img;

   public static void main(String[] args) {
        BufferedImage img =new BufferedImage(100, 50,BufferedImage.TYPE_INT_ARGB); 
        //textField = new JTextField();
        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 paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);

        Graphics2D i = img.createGraphics();
       Color myColor = Color.decode("#32004b");
       i.setColor(myColor);
       i.fillRect(x,y,w,h);

           // g.fillRect(10,10,10,10);
    }

    public Test() {

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


                //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 void actionPerformed(ActionEvent e) {

        Graphics g= getGraphics();
        textField.addActionListener(this);

               if (e.getSource() == textField) {
                   entry= Integer.parseInt(textField.getText());
                   g.drawString("Test",50,50);

                   entry=h;

                }         
    }
}
4

3 回答 3

1

你在做

JTextField textField=new JTextField();

在创建新局部变量但JTextField textField;从未分配全局变量的主要方法中。在您的 actionPerformed 中,您使用的textField是从未初始化的全局变量。

于 2012-04-13T20:11:05.577 回答
1

将变量声明为

     private static JTextField textField;

删除“JTextField”并将其用作

     textField = new JTextField();

在你的主要方法中

于 2012-04-13T21:20:33.703 回答
0

我会在你的主要方法中替换这一行:

JTextField textField=new JTextField();

用这些:

textField=new JTextField();
textField.addActionListener(this);

然后我会从你的actionPerformed方法中删除这一行:

textField.addActionListener(this);
于 2012-04-13T20:13:07.493 回答