主题:请教高手,解决以下问题
我想实现:
在面板的黑色和红色区域中单击,在单击的地方出现一个白色的圆.单击其他地方,原来的圆消失,在新的地方出现白色的圆.
我写的程序在下面,有错误,没达到我的要求,那位大侠帮帮忙!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaTest extends JFrame {
JButton b=new JButton("button");
JTextField tf=new JTextField("txet");
public JavaTest(){
Container con=this.getContentPane();
con.setLayout(null);
PaintRect pr=new PaintRect();
pr.setBounds(new Rectangle(2,2,290,200));
pr.setBorder(BorderFactory.createLineBorder(Color.red));
con.add(pr);
b.setBounds(new Rectangle(20,220,100,30));
con.add(b);
tf.setBounds(new Rectangle(160,220,120,30));
con.add(tf);
//面板上有一个矩形区、一个JButton和一个JTextField
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
//在下面条件下,画白色的圆
if(x>=2 && x<=292 && y>=2 && y<=202){
PaintCircle pc=new PaintCircle(e.getX(),e.getY());
pc.setBounds(new Rectangle(x,y,10,10));
getContentPane().add(pc);
}
}
});
this.setSize(300,300);
}
public static void main(String args[]){
JavaTest jt=new JavaTest();
jt.setVisible(true);
}
}
class PaintCircle extends JPanel{
int cx;
int cy;
public PaintCircle(int x,int y){
cx=x;cy=y;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.drawOval(cx,cy,10,10);
}
}
class PaintRect extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(2,2,145,195);
g.setColor(Color.red);
g.fillRect(2,147,140,195);
}
}
在面板的黑色和红色区域中单击,在单击的地方出现一个白色的圆.单击其他地方,原来的圆消失,在新的地方出现白色的圆.
我写的程序在下面,有错误,没达到我的要求,那位大侠帮帮忙!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaTest extends JFrame {
JButton b=new JButton("button");
JTextField tf=new JTextField("txet");
public JavaTest(){
Container con=this.getContentPane();
con.setLayout(null);
PaintRect pr=new PaintRect();
pr.setBounds(new Rectangle(2,2,290,200));
pr.setBorder(BorderFactory.createLineBorder(Color.red));
con.add(pr);
b.setBounds(new Rectangle(20,220,100,30));
con.add(b);
tf.setBounds(new Rectangle(160,220,120,30));
con.add(tf);
//面板上有一个矩形区、一个JButton和一个JTextField
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
//在下面条件下,画白色的圆
if(x>=2 && x<=292 && y>=2 && y<=202){
PaintCircle pc=new PaintCircle(e.getX(),e.getY());
pc.setBounds(new Rectangle(x,y,10,10));
getContentPane().add(pc);
}
}
});
this.setSize(300,300);
}
public static void main(String args[]){
JavaTest jt=new JavaTest();
jt.setVisible(true);
}
}
class PaintCircle extends JPanel{
int cx;
int cy;
public PaintCircle(int x,int y){
cx=x;cy=y;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.drawOval(cx,cy,10,10);
}
}
class PaintRect extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(2,2,145,195);
g.setColor(Color.red);
g.fillRect(2,147,140,195);
}
}