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;
}
}
}
重複的[我不知道如何從我的文本字段中獲取數據](http://stackoverflow.com/questions/10145493/im-not-sure-how-to-get-the- data-from-my-text-field) – trashgod 2012-04-13 21:02:29
隨機評論:a)you _must_在paintComponent中調用super b)有兩個JFrames c)在getPref中返回一個硬編碼大小沒有意義我);評論線是要走的路d)永遠不要使用getGraphics e)永遠不要使用setBounds f)爲什麼你要在圖像的圖形上繪畫......總之(沒有冒犯的意思):你的代碼是一團糟。我建議你退後一步,在教科書的第一頁重新開始 – kleopatra 2012-04-14 07:26:14