【Swing】 paintImmediately 的效率问题若干

raistlic raistlic 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

在一个游戏里用了 paintImmediately 来刷新某 JComponent c

c 为 opaque,空布局,没有子控件

用 System.currentTimeMillis() 取时间差测得 c 的 paintComponent() 方法耗时为 0 ms

c.paintImmediatly 的每次调用却耗时 15 ~ 16 ms 不等,这正常吗?


我测量的方法正确吗?


有没有什么办法改进 paintImmediatly 的效率?

如果不用 paintImmediatly,有什么办法可以安全的得到一个往屏幕上绘制 c 的 Graphics 对象?
...全文

相关推荐

swing文件拖拽

实现文件的拖拽功能 import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.Timer; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; class DragTree extends JTree implements DragGestureListener, DragSourceListener, DropTargetListener { /** * */ private static final long serialVersionUID = 1L; BufferedImage ghostImage; private Rectangle2D ghostRect = new Rectangle2D.Float(); private Point ptOffset = new Point(); private Point lastPoint = new Point(); private TreePath lastPath; private Timer hoverTimer; FileNode sourceNode; public DragTree() { DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(this, // component where // drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer setModel(createTreeModel()); addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { } public void treeExpanded(TreeExpansionEvent e) { TreePath path = e.getPath(); if (path != null) { FileNode node = (FileNode) path.getLastPathComponent(); if (!node.isExplored()) { DefaultTreeModel model = (DefaultTreeModel) getModel(); node.explore(); model.nodeStructureChanged(node); } } } }); this.setCellRenderer(new DefaultTreeCellRenderer() { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { TreePath tp = tree.getPathForRow(row); if (tp != null) { FileNode node = (FileNode) tp.getLastPathComponent(); File f = node.getFile&#40;&#41;; try { Icon icon = FileSystemView.getFileSystemView() .getSystemIcon(f); this.setIcon(icon); this.setLeafIcon(icon); this.setOpenIcon(icon); this.setClosedIcon(icon); this.setDisabledIcon(icon); } catch (Exception e) { e.printStackTrace(); } } return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); } }); super.setScrollsOnExpand(true); new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); // Set up a hover timer, so that a node will be automatically expanded // or collapsed // if the user lingers on it for more than a short time hoverTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (lastPath == null) { return; } if (getRowForPath(lastPath) == 0) return; // Do nothing if we are hovering over the root node if (isExpanded(lastPath)) collapsePath(lastPath); else expandPath(lastPath); } }); hoverTimer.setRepeats(false); // Set timer to one-shot mode this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); int modifiers = e.getModifiers(); if (code == 'v' || code == 'V') { System.out.println("find v"); System.out.println("modifiers:" + modifiers + "\t" + ((modifiers & KeyEvent.CTRL_MASK) != 0)); } if ((modifiers & KeyEvent.CTRL_MASK) != 0 && (code == 'v' || code == 'V')) { Transferable tr = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); TreePath path = getSelectionPath(); if (path == null) { return; } FileNode node = (FileNode) path.getLastPathComponent(); if (node.isDirectory()) { System.out.println("file cp"); try { List list = (List) (tr .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent = node.getFile&#40;&#41;; while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File&#40;parent, f.getName(&#41;)); } node.reexplore(); } catch (Exception ioe) { ioe.printStackTrace(); } updateUI(); } } } }); } public void dragGestureRecognized(DragGestureEvent e) { // drag anything ... TreePath path = getLeadSelectionPath(); if (path == null) return; FileNode node = (FileNode) path.getLastPathComponent(); sourceNode = node; // Work out the offset of the drag point from the TreePath bounding // rectangle origin Rectangle raPath = getPathBounds(path); Point ptDragOrigin = e.getDragOrigin(); ptOffset.setLocation(ptDragOrigin.x - raPath.x, ptDragOrigin.y - raPath.y); // Get the cell renderer (which is a JLabel) for the path being dragged int row = this.getRowForLocation(ptDragOrigin.x, ptDragOrigin.y); JLabel lbl = (JLabel) getCellRenderer().getTreeCellRendererComponent( this, // tree path.getLastPathComponent(), // value false, // isSelected (dont want a colored background) isExpanded(path), // isExpanded getModel().isLeaf(path.getLastPathComponent()), // isLeaf row, // row (not important for rendering) false // hasFocus (dont want a focus rectangle) ); lbl.setSize((int) raPath.getWidth(), (int) raPath.getHeight()); // <-- // The // layout // manager // would // normally // do // this // Get a buffered image of the selection for dragging a ghost image this.ghostImage = new BufferedImage((int) raPath.getWidth(), (int) raPath.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = ghostImage.createGraphics(); // Ask the cell renderer to paint itself into the BufferedImage g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f)); // Make the image ghostlike lbl.paint(g2); g2.dispose(); // this.getGraphics().drawImage(ghostImage, e.getDragOrigin().x, // e.getDragOrigin().y, this); e.startDrag( null, // cursor ghostImage, new Point(5, 5), new StringSelection(getFilename()), // transferable this); // drag source listener } public void dragDropEnd(DragSourceDropEvent e) { ghostImage = null; sourceNode = null; } public void dragEnter(DragSourceDragEvent e) { } public void dragExit(DragSourceEvent e) { if (!DragSource.isDragImageSupported()) { repaint(ghostRect.getBounds()); } } public void dragOver(DragSourceDragEvent e) { } public void dropActionChanged(DragSourceDragEvent e) { } public String getFilename() { TreePath path = getLeadSelectionPath(); FileNode node = (FileNode) path.getLastPathComponent(); return ((File) node.getUserObject()).getAbsolutePath(); } private DefaultTreeModel createTreeModel() { File root = FileSystemView.getFileSystemView().getRoots()[0]; FileNode rootNode = new FileNode(root); rootNode.explore(); return new DefaultTreeModel(rootNode); } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { Point pt = dtde.getLocation(); if (pt.equals(lastPoint)) { return; } if (ghostImage != null) { Graphics2D g2 = (Graphics2D) getGraphics(); // If a drag image is not supported by the platform, then draw my // own drag image if (!DragSource.isDragImageSupported()) { paintImmediately(ghostRect.getBounds()); // Rub out the last // ghost image and cue // line // And remember where we are about to draw the new ghost image ghostRect.setRect(pt.x - ptOffset.x, pt.y - ptOffset.y, ghostImage.getWidth(), ghostImage.getHeight()); g2.drawImage((ghostImage), AffineTransform .getTranslateInstance(ghostRect.getX(), ghostRect.getY()), null); } } TreePath path = getClosestPathForLocation(pt.x, pt.y); if (!(path == lastPath)) { lastPath = path; hoverTimer.restart(); } } public void dropActionChanged(DropTargetDragEvent dtde) { } public void drop(DropTargetDropEvent e) { try { DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); TreePath path = this.getPathForLocation(e.getLocation().x, e.getLocation().y); if (path == null) { e.rejectDrop(); return; } FileNode node = (FileNode) path.getLastPathComponent(); if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor) && node.isDirectory()) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); System.out.println("file cp"); List list = (List) (e.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent = node.getFile&#40;&#41;; while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File&#40;parent, f.getName(&#41;)); } node.reexplore(); e.dropComplete(true); this.updateUI(); } else if (e.isDataFlavorSupported(stringFlavor) && node.isDirectory()) { String filename = (String) tr.getTransferData(stringFlavor); if (filename.endsWith(".txt") || filename.endsWith(".java") || filename.endsWith(".jsp") || filename.endsWith(".html") || filename.endsWith(".htm")) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); File f = new File&#40;filename&#41;; if (f.exists()) { f.renameTo(new File&#40;node.getFile(&#41;, f.getName())); node.reexplore(); ((FileNode) sourceNode.getParent()).remove(sourceNode); e.dropComplete(true); this.updateUI(); } else { e.rejectDrop(); } } else { e.rejectDrop(); } } else { e.rejectDrop(); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } finally { ghostImage = null; this.repaint(); } } private void cp(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { boolean ret = dest.mkdir(); if (ret == false) return; } File[] fs = src.listFiles(); for (int i = 0; i < fs.length; i++) { cp(fs[i], new File&#40;dest, fs[i].getName(&#41;)); } return; } byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int len; try { while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { in.close(); out.close(); } } public void dragExit(DropTargetEvent dte) { } } class FileNode extends DefaultMutableTreeNode { private boolean explored = false; public FileNode(File file) { setUserObject(file); } public boolean getAllowsChildren() { return isDirectory(); } public boolean isLeaf() { return !isDirectory(); } public File getFile&#40;&#41; { return (File) getUserObject(); } public boolean isExplored() { return explored; } public boolean isDirectory() { File file = getFile&#40;&#41;; return file.isDirectory(); } public String toString() { File file = (File) getUserObject(); String filename = file.toString(); int index = filename.lastIndexOf(File.separator); return (index != -1 && index != filename.length() - 1) ? filename .substring(index + 1) : filename; } public void explore() { if (!isDirectory()) return; if (!isExplored()) { File file = getFile&#40;&#41;; File[] children = file.listFiles(); for (int i = 0; i < children.length; ++i) { if (children[i].isDirectory()) add(new FileNode(children[i])); } for (int i = 0; i < children.length; ++i) { if (!children[i].isDirectory()) add(new FileNode(children[i])); } explored = true; } } public void reexplore() { this.removeAllChildren(); explored = false; explore(); } }

ld83121

STM32F4 彩屏显示入门实验,含屏幕驱动和例程,新手可照着跑

这是我整理的 STM32F4 入门实验工程。里面有 TFT 彩屏显示驱动,还配了面包板上的 LED、按键这些基础外设,接线图也写了。刚开始学单片机的同学照着接就能亮屏,不用到处找例程。代码注释比较全,改参数就能换成自己的项目

2601_97255056

Delphi 13.2控件之DBX-0.6.26-x64-setup.exe.zip

Delphi 13.2控件之DBX_0.6.26_x64-setup.exe.zip

tjsoft

基于神经网络与ANFIS的自适应MPC车辆轨迹跟踪仿真研究(Matlab代码、Simulink仿真实现)

内容概要:本研究聚焦于基于神经网络与自适应神经模糊推理系统(ANFIS)优化的模型预测控制(MPC),实现对无人驾驶车辆轨迹的高精度跟踪。通过Matlab/Simulink搭建完整的车辆动力学模型与控制系统仿真环境,综合运用神经网络强大的非线性拟合能力与ANFIS的模糊逻辑推理优势,对传统MPC的预测模型或权重参数进行在线自适应调整,有效应对车辆系统在不同工况下的参数不确定性、外部干扰及强非线性问题。研究涵盖了从理论建模、算法设计到仿真验证的全过程,旨在提升MPC控制器在复杂动态环境下的鲁棒性和控制精度,确保车辆能够精确地沿预设轨迹(如双移线)行驶。; 适合人群:具备车辆动力学、自动控制原理和Matlab/Simulink仿真基础的研究生、科研人员及自动驾驶领域的算法工程师。; 使用场景及目标:① 研究和开发高级自动驾驶车辆的横向与纵向协同控制策略;② 解决传统MPC在面对模型失配和未知扰动时性能下降的问题,提升轨迹跟踪的鲁棒性;③ 为相关领域的学术研究(如硕士论文复现)和工程实践提供可复用的仿真代码和技术路线。; 阅读建议:学习者应重点关注神经网络与ANFIS是如何与MPC框架相结合的,理解其自适应机制的设计原理,并动手运行提供的Matlab代码和Simulink模型,通过调整参数和工况来观察控制效果的变化,从而深入掌握该复合控制策略的核心思想与实现细节。

三伯

地下矿井背包灭火器假人检测数据集VOC+YOLO格式2471张4类别.md

亲爱的CSDN用户: 首先感谢你点进这个资源页面。我需要提前说明一个重要情况: **本资源原本已设置为“0积分下载”**,即作者希望完全免费共享。但CSDN平台有时会根据文件的下载热度、文件大小、用户权限等因素,**自动将部分资源的积分调整为非0数值**(如1积分、2积分、5积分等)。这是平台系统的自动行为,而非作者本人的设定。 **因此,如果你当前看到该资源的下载所需积分不是0(例如显示为1、2、3……),请谨慎决定是否下载。** 如果你按照非0积分支付并下载后发现资源内容不符合预期、链接失效,或者实际上该资源本应是免费的,作者无法为此承担积分损失或退还操作。**强烈建议:仅在页面显示为0积分时进行下载。** 另外,本资源描述中**并未直接提供具体的下载地址或外部链接**,因为它本身是一个通过CSDN官方上传通道提交的文件/内容包。如果你看到描述中没有外部网盘地址,这是正常的——资源文件应通过CSDN内置的“下载”按钮获取。若因平台积分显示异常导致你支付了积分,请优先联系CSDN客服咨询积分退还政策,作者没有权限修改平台自动设定的积分值。 感谢你的理解与支持。技术分享本应开放,但受限于平台规则,特此提醒如上。祝学习进步!

fl176831
评论 10
收藏 已收藏
分享
返回顶部
raistlic
Java SE 62,620 成员 307,251 内容