zoukankan      html  css  js  c++  java
  • JPanel 的getGraphics

    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class TestPen extends JFrame {
        Graphics redPen ;
        public TestPen(){
            setSize(500,500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            final JPanel p = new JPanel();
            add(p,BorderLayout.CENTER);
            JButton bt = new JButton("获取画笔");
            bt.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    redPen = getGraphics();
                    //redPen = p.getGraphics();也OK
                    redPen.setColor(Color.RED);
                }
            });
            add(bt,BorderLayout.SOUTH);
            p.setBorder(BorderFactory.createTitledBorder("PP"));
            addMouseMotionListener(new MouseAdapter(){
                public void mouseDragged(MouseEvent e ) {
                    if (redPen==null) return;
                    redPen.fillOval(e.getX(), e.getY(), 5, 5);
                }
            });
            setVisible(true);
        }
        public void init(){
            redPen = getGraphics();
            redPen.setColor(Color.RED);
            addMouseMotionListener(new MouseAdapter(){
                public void mouseDragged(MouseEvent e ) {
                    redPen.fillOval(e.getX(), e.getY(), 10, 10);
                }
            });
        }
        public static void main(String[] args ) {
            
            new TestPen();
            
        }
    
    }

    因为在所有组件还没画出时,是不能获得Graphics的,只会返回空.只有在JFrame全部显示后才能get到Graphics.所以把他们放到事件中,手动获得.就可以.这样画图也不用重写paint. 但这个是临时的,最大化最小化后画的就没有了.

  • 相关阅读:
    看到关于java资料比较全的,自己收藏
    ie6下pnghack——css方案
    git基本操作
    购物车功能实现
    jquery学习:获取位置position(),offset(),scrollTop困惑
    Datax3.0使用说明
    Scala字符串操作
    Scala中class、object、case class、case object区别
    Scala构造函数
    scala数组操作
  • 原文地址:https://www.cnblogs.com/qqjue/p/2630453.html
Copyright © 2011-2022 走看看