我试图在这个GUI中创建一个文本字段(下面的变量查询),如果它注意到按下某个键,GUI将绘制出键入文本字段的字符串。但是,如果我将我的字符串str初始化为“”它在GUI上保持为“”并且永远不会改变,但是当我在paintComponent方法中打印出字符串时,它具有正确的字符串(由于某种原因除了最后一个字符)。有小费吗?提前谢谢!
private String str;
private JTextField query;
public void keyPressed(KeyEvent e) {
str = query.getText();
}
...
public void paintComponent(Graphics g){
super.paintComponent(g);
//System.out.println(str);
g.drawString(str,20,30);
}
答案 0 :(得分:4)
KeyListener
与任何JTextComponent
一起使用,这不是监控这些组件更改的适当方法,而是使用DocumentListener
,这将在字段修改时通知通过调用setText
或者将文本粘贴到字段中以及用户键入内容时您还应该避免直接绘制到组件上的相同组件,因为布局管理器可以将内容放在自定义绘制的顶部
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private String paintText;
public TestPane() {
JTextField field = new JTextField(10);
add(field);
field.getDocument().addDocumentListener(new DocumentListener() {
protected void update(DocumentEvent e) {
Document doc = e.getDocument();
try {
paintText = doc.getText(0, doc.getLength());
repaint();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
@Override
public void insertUpdate(DocumentEvent e) {
update(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
update(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
update(e);
}
});
field.setText("This is some text");
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(paintText)) / 2;
int y = ((getHeight() - fm.getHeight()) + fm.getAscent()) / 2;
g2d.drawString(paintText, x, y);
g2d.dispose();
}
}
}