【发布时间】:2011-09-18 21:26:54
【问题描述】:
我希望能够在 JFrame 上使用 Java 的 paint() 进行绘制。当我单击 JFrame(现在任何地方)时,我希望使用单击的坐标重新绘制 JFrame - 类似于这个 Java 小程序 http://www.realapplets.com/tutorial/MouseClickExample.html
目前工作:
- 最初绘制所有内容并正确显示 JFrame
不工作:
- 即使声明了 repaint(),JFrame 也不会重新绘制和更新
这是我的代码 - 请尽可能严格 - 我想改进我的 Java 编程技术,所以(如果你有时间的话)指出我可以改进的每一个方面。
非常感谢任何帮助。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AreaForText extends JPanel implements MouseListener {
int xpos;
int ypos;
JFrame myJFrame = new JFrame();
public void setJFrame() {
myJFrame.setSize(300, 150);
myJFrame.setTitle("Bigger Text!");
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myJFrame.setVisible(true);
myJFrame.getContentPane().add(new AreaForText());
myJFrame.addMouseListener(new AreaForText());
}
public void mouseClicked(MouseEvent me) {
//Save the coordinates of the click lke this.
xpos = MouseInfo.getPointerInfo().getLocation().x;
ypos = MouseInfo.getPointerInfo().getLocation().y;
System.out.print("Click" + " x: " + xpos + " y: " + ypos);
myJFrame.invalidate();
repaint();
revalidate();
}
public void mouseEntered(MouseEvent e){
}
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void paint(Graphics g) {
System.out.print("hello");
g.drawString("Hello World", 30, 80);
g.fillRect(20,20,20,20);
g.drawString("("+xpos+","+ypos+")",xpos,ypos);
}
}
class EnlargeText {
public static void main(String args[]) {
AreaForText test = new AreaForText();
test.setJFrame();
}
}
【问题讨论】:
-
干得好,包括一个工作代码示例,在您的第一个问题上格式正确!
-
代码中不需要使用invalidate()和revalidate()。
标签: java awt jframe validation repaint