2012-04-13 64 views
0

我的文本字段没有被添加到我的Jframe中,我想让这个文本字段可用,以便我可以使用它来改变绘制在paint中的矩形的高度。在actionperfomred IM试图从该字段的值,并希望这将重新绘制图像正确的值不添加TextField到jFrame

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; 

    public void init(){ 
     JTextField textField=new JTextField(); 
     f.add(textField); 
     textField.setBounds(10,10,40,30); 
     textField.setVisible(true); 
     textField.addActionListener(this); 
    } 

    // 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"); 

     /*textField=new JTextField(); 
     textField.addActionListener(this); 
     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(); 


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

        entry=h; 

       } 

    } 
} 
+1

重复的[我不知道如何从我的文本字段中获取数据](http://stackoverflow.com/questions/10145493/im-not-sure-how-to-get-the- data-from-my-text-field) – trashgod 2012-04-13 21:02:29

+0

随机评论:a)you _must_在paintComponent中调用super b)有两个JFrames c)在getPref中返回一个硬编码大小没有意义我);评论线是要走的路d)永远不要使用getGraphics e)永远不要使用setBounds f)为什么你要在图像的图形上绘画......总之(没有冒犯的意思):你的代码是一团糟。我建议你退后一步,在教科书的第一页重新开始 – kleopatra 2012-04-14 07:26:14

回答

2

我想这是因为你永远不调用该方法的init

2

打电话给你的init方法和你会没事