实现鼠标点击的位置,再已有背景的JPanel控件中增加一副小图片。

解决方案 »

  1.   

    public class MyDrawPanel extends JPanel{ public MyDrawPanel(){
    MediaTracker media = new MediaTracker(this);
    media.addImage(img1, 0);
    media.addImage(img2, 1);
    media.addImage(img3, 2);
    try {
    media.waitForAll();
    } catch (Exception e) {
    }
    }

    public void paintComponent(Graphics g) 

    g.drawImage(img1, 0, 0, null);
    }
    }只写到了这里,后面的就不知道怎么办了
      

  2.   

    在鼠标点击处理程序中,
    Graphics g=jPanel.getGraphics();
    g.drawImage();//在鼠标的位置画图,自己写
      

  3.   

    可以这样写么?
    JPanel本身是不能直接画图的吧?有些人说必须重写paintComponent方法才可以
      

  4.   

    额?
    由于是在JFrame中添加的一个绘图JPanel,用getGraphics()之后,JFrame变成透明了
      

  5.   

    重写paintComponent方法比较难实现在原有的基础上画图
    getGraphics(); 比较灵活
      

  6.   

    getGraphics()是面板调用的,不是窗体调用,你是不是用错了?
      

  7.   

    jpanel.getGraphics() = null 不能画图
      

  8.   

    public class MyDrawPanel extends JPanel{
    Graphics g;

    public MyDrawPanel(){
    MediaTracker media = new MediaTracker(this);
    media.addImage(img1, 0);
    media.addImage(img2, 1);
    media.addImage(img3, 2);
    try {
    media.waitForAll();// 等待所有图片加载完成
    } catch (Exception e) {
    }
    g = this.getGraphics();
    }

    public void paint(Graphics g) {
    g.drawImage(img2, 5, 25, null);
    drawtest();
    }//#paint public void Refresh() {
    this.update(g);
    } public void drawtest() {
    g.drawImage(im1, 123, 345, null);
    }//#showChress
    }然后在JFrame里面 new MyDrawPanel();
      

  9.   

    我临时写的,只画直线,你改为画图片就行,很多是初始化的,可以不看import java.awt.Graphics;
    public class TestDraw extends javax.swing.JFrame {    /** Creates new form TestDraw */
        public TestDraw() {
            initComponents();
        }    /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {        jPanel = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel);
            jPanel.setLayout(jPanelLayout);
            jPanelLayout.setHorizontalGroup(
                jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            jPanelLayout.setVerticalGroup(
                jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 243, Short.MAX_VALUE)
            );        jButton1.setText("绘图");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addGap(158, 158, 158)
                    .addComponent(jButton1)
                    .addContainerGap(185, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(16, 16, 16)
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );        pack();
        }// </editor-fold>    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
             Graphics g=jPanel.getGraphics();
             g.drawLine(0, 0, 100, 100);
             g.drawLine(50, 0,0, 300);
        }    /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestDraw().setVisible(true);
                }
            });
        }    // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel;
        // End of variables declaration}
      

  10.   

    可能你要在jPanel=new MyDrawPanel();之后,在窗体中调用Graphics g=jPanel.getGraphics();才行
      

  11.   

    设置一下JLyeredPanel中的Z-Order数值就可以了。。
      

  12.   

    看看这个:package paintDemo;import java.awt.Color;
    import java.awt.Shape;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Rectangle2D;
    import java.io.Serializable;public abstract class MyShape implements Serializable{
    private Color color;
    public abstract Shape getShape();

    public static class Line extends MyShape{
    private Line2D line;
    public Line(int x1,int y1,int x2,int y2,Color c){
    line=new Line2D.Double(x1,y1,x2,y2);
    this.setColor(c);
    }
    public Shape getShape(){
    return line;
    }
    }

    public static class Ellipse extends MyShape{
    private Ellipse2D ell;
    public Ellipse(int x1,int y1,int x2,int y2,Color c){
    ell=new Ellipse2D.Double(Math.min(x1,x2),Math.min(y1, y2),
    Math.abs(x1-x2),Math.abs(y1-y2));
    this.setColor(c);
    }
    public Shape getShape(){
    return ell;
    }
    }

    public static class Rectangle extends MyShape{
    private Rectangle2D rect;
    public Rectangle(int x1,int y1,int x2,int y2,Color c){
    rect=new Rectangle2D.Double(Math.min(x1,x2),Math.min(y1, y2),
    Math.abs(x1-x2),Math.abs(y1-y2));
    this.setColor(c);
    }
    public Shape getShape(){
    return rect;
    }
    } public Color getColor() {
    return color;
    } public void setColor(Color color) {
    this.color = color;
    }}
    package paintDemo;import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.ArrayList;import javax.swing.JPanel;public class PaintArea extends JPanel{
    private MyShape shape;
    private ArrayList<MyShape> list=new ArrayList<MyShape>();
    private int type;//0 线,1 圆,2 矩形
    private Color color;


    public MyShape getShape() {
    return shape;
    } public void setShape(MyShape shape) {
    this.shape = shape;
    } public void setType(int type) {
    this.type = type;
    } public void setColor(Color color) {
    this.color = color;
    }

    public void newShape(int x1, int y1, int x2, int y2) {
    if(type==0){
    shape=new MyShape.Line(x1,y1,x2,y2,color);
    }else if(type==1){
    shape=new MyShape.Ellipse(x1,y1,x2,y2,color);
    }else{
    shape=new MyShape.Rectangle(x1,y1,x2,y2,color);
    }
    } // public void setShape(int x1,int y1,int x2,int y2){
    // shape=new MyShape
    // }
    public void paint(Graphics g){
    g.clearRect(0, 0, this.getWidth(), this.getHeight());
    Graphics2D g2 = (Graphics2D) g; for (int i = 0; i < list.size(); i++) {
    MyShape temp = list.get(i);
    g2.setColor(temp.getColor());
    g2.draw(temp.getShape());
    } if (shape != null) {
    g2.setColor(shape.getColor());
    g2.draw(shape.getShape());
    }
    } public int getType() {
    return type;
    } public Color getColor() {
    return color;
    }
    public void addShape(){
    list.add(shape);
    }

    //清除方法
    public void clear(){
    list.clear();
    shape=null;
    this.repaint();
    } public ArrayList<MyShape> getList() {
    return list;
    } public void setList(ArrayList<MyShape> list) {
    this.list = list;
    }}
      

  13.   

    接上面:package paintDemo;import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.EOFException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.ArrayList;import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToggleButton;
    import javax.swing.JToolBar;public class PaintDemo extends JFrame{
    private JToggleButton but[];
    private JButton butop[];
    private JToolBar bar;
    private JPanel opBar;
    private PaintArea paintArea;
    private JLabel lab[];
    public PaintDemo(){
    super("Paint demo");
    // this.setLayout(new BorderLayout());
    this.setBounds(200,200,400,300);

    but=new JToggleButton[]{new JToggleButton("线",true),new JToggleButton("圆"),new JToggleButton("矩形"),
    new JToggleButton("黑",true),new JToggleButton("红"),new JToggleButton("绿"),new JToggleButton("蓝")};
    ButtonGroup g1=new ButtonGroup();
    ButtonGroup g2=new ButtonGroup();
    g1.add(but[0]);
    g1.add(but[1]);
    g1.add(but[2]);
    g2.add(but[3]);
    g2.add(but[4]);
    g2.add(but[5]);
    g2.add(but[6]);

    butop=new JButton[]{new JButton("清除"),new JButton("保存"),new JButton("打开")};
    bar=new JToolBar();
    for(int i=0;i<but.length;i++){
    if(i==3){
    bar.addSeparator();
    }
    bar.add(but[i]);
    but[i].addActionListener(new ButHandler());

    }
    bar.addSeparator();
    bar.add(butop[0]);
    bar.addSeparator();
    bar.add(butop[1]);
    bar.add(butop[2]);

    this.add(bar,BorderLayout.NORTH);

    //状态栏
    lab=new JLabel[]{new JLabel("图形:线"),new JLabel("颜色")};
    lab[1].setOpaque(true);
    opBar=new JPanel();
    opBar.setLayout(new FlowLayout(FlowLayout.LEFT,30,2));
    opBar.setBorder(BorderFactory.createEtchedBorder());
    opBar.add(lab[0]);
    opBar.add(lab[1]);
    setLabColor(Color.BLACK);
    this.add(opBar,BorderLayout.SOUTH);

    //画布
    paintArea=new PaintArea();
    this.add(paintArea);
    paintArea.setColor(Color.BLACK);
    paintArea.setType(0);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);

    //添加监听器
    Handler h=new Handler();
    paintArea.addMouseListener(h);
    paintArea.addMouseMotionListener(h);

    for(JButton b:butop){
    b.addActionListener(new OpButHandler());
    }
    }

    public void setLabColor(Color c){
    int r=c.getRed();
    int g=c.getGreen();
    int b=c.getBlue();
    Color fontColor=new Color(255-r,255-g,255-b);
    lab[1].setForeground(fontColor);
    lab[1].setBackground(c);
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
    new PaintDemo();
    }

    class Handler extends MouseAdapter{
    private int x1,y1;
    public void mousePressed(MouseEvent arg0) {
    this.x1=arg0.getX();
    this.y1=arg0.getY();
    System.out.println(x1+"  "+y1);
    } public void mouseReleased(MouseEvent arg0) {
    paintArea.addShape();
    } public void mouseDragged(MouseEvent arg0) {
    paintArea.newShape(x1, y1, arg0.getX(),arg0.getY());
    paintArea.repaint();
    }
    }

    class ButHandler implements ActionListener{ public void actionPerformed(ActionEvent e) {
    if(e.getSource()==but[0]){
    paintArea.setType(0);
    lab[0].setText("图形:线");
    }
    if(e.getSource()==but[1]){
    paintArea.setType(1);
    lab[0].setText("图形:圆");
    }
    if(e.getSource()==but[2]){
    paintArea.setType(2);
    lab[0].setText("图形:矩形");
    }
    if(e.getSource()==but[3]){
    paintArea.setColor(Color.BLACK);
    setLabColor(Color.BLACK);
    }
    if(e.getSource()==but[4]){
    paintArea.setColor(Color.RED);
    setLabColor(Color.RED);
    }
    if(e.getSource()==but[5]){
    paintArea.setColor(Color.GREEN);
    setLabColor(Color.GREEN);
    }
    if(e.getSource()==but[6]){
    paintArea.setColor(Color.BLUE);
    setLabColor(Color.BLUE);
    }
    }

    }
    class OpButHandler implements ActionListener{ public void actionPerformed(ActionEvent a) {
    if(a.getSource()==butop[0]){
    paintArea.clear();
    }
    if(a.getSource()==butop[1]){
    JFileChooser save=new JFileChooser();
    save.showSaveDialog(null);
    File afile=save.getSelectedFile();
    if(afile!=null){
    savePic(afile);
    }

    }
    if(a.getSource()==butop[2]){
    JFileChooser open=new JFileChooser();
    open.showOpenDialog(null);
    File afile=open.getSelectedFile();
    if(afile!=null){
    ArrayList<MyShape> list=openPic(afile);
    paintArea.setList(list);
    paintArea.setShape(null);
    paintArea.repaint();
    }
    }
    }

    }

    public void savePic(File afile){
    ArrayList<MyShape> list=paintArea.getList();
    try {
    FileOutputStream fo=new FileOutputStream(afile);
    ObjectOutputStream objout=new ObjectOutputStream(fo);
    for(MyShape s:list){
    objout.writeObject(s);
    }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

    public ArrayList<MyShape> openPic(File afile){
    ArrayList<MyShape> list=new ArrayList<MyShape>();

    try {
    FileInputStream fi=new FileInputStream(afile);
    ObjectInputStream objin=new ObjectInputStream(fi);
    while(true){
    list.add((MyShape)objin.readObject());
    }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }catch (EOFException e) {
    System.out.println("到文件尾.....");
    }catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return list;
    }}
      

  14.   

    上面的回复太麻烦,对楼主只有两点建议:
    一。重写paintComponent方法;
    二。在主程序中不要忘记repaint()方法的调用,解释:paintComponent方法的重载建议楼主随便找本书看下都有的
          至于repaint,呵呵呵呵。