日期:2014-05-20  浏览次数:20735 次

怎样将JPanel置空?
本帖最后由 t13977168314 于 2013-06-04 22:01:46 编辑
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;

public class MouseColor extends JFrame{
public MouseColor(){
Point p=new Point();
add(p);

}
public static void main(String[] args){
MouseColor frame=new MouseColor();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(500,400);
}

static class Point extends JPanel{
private int x=0;
private int y=0;
private String str=" ";
public  Point(){
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
x=e.getX();
y=e.getY();
str="("+x+","+y+")";
repaint();
}
public void mouseReleased(MouseEvent e){
//当鼠标释放时清除显示的坐标,即显示为空面板
}

});
}
protected void paintComponent(Graphics g){
super.paintComponents(g);
g.drawString(str, x, y);
}
}
}

------解决方案--------------------
static class Point extends JPanel {
private int x = 0;
private int y = 0;
private String str = " ";
private boolean clear;

public Point() {
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
clear = false;
x = e.getX();
y = e.getY();
str = "(" + x + "," + y + ")";
repaint();
}

public void mouseReleased(MouseEvent e) {
// 当鼠标释放时清除显示的坐标,即显示为空面板
clear = true;
repaint();
}
});
}

protected void paintComponent(Graphics g) {
if (!clear) {
super.paintComponents(g);
g.drawString(str, x, y);
}
else {
        g.clearRect(0, 0, getWidth(), getHeight());
}
}
}

重绘一下^_^
------解决方案--------------------
1、你代码中 super.paintComponents(g); 改为 super.paintComponent(g); 
2、至于两个函数的区别,你查API吧。
3、加一个标示,用于处理repaint
 



import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;

public class MouseColor extends JFrame{
public MouseColor(){
Point p=new Point();
add(p);

}
public static void main(String[] args){
MouseColor frame=new MouseColor();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(500,400);