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. 但这个是临时的,最大化最小化后画的就没有了.

  • 相关阅读:
    《剑指Offer》二维数组中的查找
    白话计算机入门书籍--《穿越计算机的迷雾》有感
    Mysql Cluster7.5.6在 windows10 部署安装
    Mysql Cluster7.5.6 windows10 部署安装
    lll
    线程控制
    动态链接库相关知识
    二分查找及其变种简单易懂的模版
    白话 STL next_permutation 原理
    Maven本地上有包还去网上找包
  • 原文地址:https://www.cnblogs.com/qqjue/p/2630453.html
Copyright © 2011-2022 走看看