栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java如何在鼠标单击上绘制矩形

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java如何在鼠标单击上绘制矩形

这是一个相对简单的概念(没有冒犯性)。

首先,请勿将代码与JApplet和混合使用Jframe。如果您想在这两种媒介中使用您的应用程序,请将逻辑分成一个单独的
组件(如JPanel),您可以轻松地将其添加到其中。您真的不应该将顶级容器添加到另一个顶级容器(在框架中添加小程序)-太麻烦了。

请避免改写paint顶层容器的方法(如JApplet),而改用自定义组件(如JPanel)并改写它的

paintComponent
方法。

在您的示例中,您应该打电话

super.paint
而不是
super.paintComponents
。paint做重要的工作,您不想跳过
它-但您应该使用JComponent#paintComponent

MouseListener应当添加到您对管理鼠标事件感兴趣的组件中。因为clicked从不添加到任何容器,所以
它将永远不会收到鼠标事件。

Take a look at

  • How to write mouse listeners
  • Performing Custom Painting
  • 2D Graphics
  • Painting in AWT and Swing (because every Swing developer should have an understanding of this)

public class SimplePaint03 {    public static void main(String[] args) {        new SimplePaint03();    }    public SimplePaint03() {        EventQueue.invokeLater(new Runnable() { @Override public void run() {     try {         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());     } catch (Exception ex) {     }     Jframe frame = new Jframe("Test");     frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);     frame.add(new PaintPane());     frame.pack();     frame.setLocationRelativeTo(null);     frame.setVisible(true); }        });    }    public class PaintPane extends JPanel {        private List<Shape> grid;        private List<Shape> fill;        public PaintPane() { grid = new ArrayList<>(5); fill = new ArrayList<>(5); addMouseListener(new MouseAdapter() {     @Override     public void mouseClicked(MouseEvent e) {         for (Shape shape : grid) {  if (shape.contains(e.getPoint())) {      if (fill.contains(shape)) {          fill.remove(shape);      } else {          fill.add(shape);      }  }         }         repaint();     } }); int colWidth = 200 / 50; int rowHeight = 200 / 50; for (int row = 0; row < 50; row++) {     for (int col = 0; col < 50; col++) {         grid.add(new Rectangle(colWidth * col, rowHeight * row, colWidth, rowHeight));     } }        }        @Override        public Dimension getPreferredSize() { return new Dimension(200, 200);        }        @Override        protected void paintComponent(Graphics g) { super.paintComponent(g);  Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); for (Shape cell : fill) {     g2d.fill(cell); } g2d.setColor(Color.BLACK); for (Shape cell : grid) {     g2d.draw(cell); }        }    }}

Additional

Information from one paint cycle to another is not maintained. You are
required to repaint the component exactly the way you want it to appear. This
means you will need to maintain a list of click points that can be repainted
at any time.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号