【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

两相交错并联BuckBoost变换器仿真模型(Simulink仿真实现)

内容概要:本文档系统整合了电力电子与新能源领域的Simulink仿真资源,聚焦于两相交错并联Buck-Boost变换器的双闭环PWM控制建模与仿真,同时涵盖多种典型拓扑结构,包括交错并联Boost、PFC功率因数校正、LLC谐振变换器、双向CLLC、DAB变换器、VIENNA整流器等。资源体系完整,包含仿真模型、设计报告、计算书、PPT说明文档及Matlab/Python代码,覆盖从基础建模到高级控制策略(如软开关技术、谐波抑制、状态估计、双闭环控制)的全流程。此外,还拓展至状态估计(卡尔曼滤波、粒子滤波)、智能优化算法、机器学习、信号处理、路径规划等多个交叉学科方向,构建了一个面向科研与工程应用的综合性技术平台。; 适合人群:电气工程、自动化、电力电子、新能源科学与工程等专业的硕士博士研究生、高校科研人员,以及从事新能源发电、智能电网、电动汽车、电力传动等领域技术研发的工程师。; 使用场景及目标:①开展电力电子变换器(如Buck-Boost、LLC、DAB、PFC等)的建模、控制与仿真研究;②支撑课程设计、学位论文、科研项目中的系统仿真与算法验证;③学习并复现高水平期刊(如EI)提出的先进控制策略,如基于KKT条件的最优控制、扩展移相调制、恒压恒流双环竞争控制等;④结合智能算法(如粒子群、秃鹰算法)进行微电网调度、储能配置、路径规划等多目标优化问题的研究与快速原型开发。; 阅读建议:建议依据提供的资源目录循序渐进地查阅资料,优先选取与自身研究方向高度契合的内容进行深入学习;应结合仿真模型与配套文档动手实践,调试参数并分析结果,充分利用百度网盘与公众号渠道获取完整资源,提升科研工作的系统性、规范性与创新性。

抬头望远方

【基于Zernike矩的良性和恶性肿块的分类】应用于乳腺癌诊断中的快速相反权重学习规则(Matlab代码实现)

内容概要:本文详细介绍了基于Plecs软件构建的全桥LLC谐振变换器仿真模型,重点阐述了其在软开关技术条件下的建模方法与仿真分析过程。该模型能够精确模拟LLC谐振变换器在不同运行工况下的动态响应特性,涵盖开环与闭环控制策略的设计与实现,适用于研究变换器的效率优化、谐振参数匹配、系统稳定性及软开关性能等问题。相较于Simulink等传统仿真工具,Plecs在高频电力电子系统仿真中展现出更高的仿真速度与数值精度,尤其适合用于复杂电力电子拓扑的快速原型验证与优化设计。; 适合人群:具备扎实电力电子技术基础和仿真经验,从事高频功率变换器设计、新能源电源开发、电力电子系统研究的研发工程师及高校研究生。; 使用场景及目标:①深入理解全桥LLC谐振变换器的工作原理与软开关实现机制;②掌握在Plecs环境中搭建高精度、高效率电力电子系统仿真模型的方法;③开展变换器控制策略(如变频控制、闭环稳压)的仿真验证与参数优化;④为科研课题、学位论文或工业项目提供可靠的仿真平台与技术支持。; 阅读建议:建议结合相关电力电子教材与LLC变换器设计指南,深入掌握谐振参数计算与系统稳定性分析方法,并通过反复调试仿真模型,观察关键波形(如原边电流零点切换、副边整流波形),以全面理解软开关过程的物理本质与控制实现细节。

荔枝科研社

高校技术转移办公室人员如何提升技术成果的推介效果和市场转化率?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

BIZKEEN

利用LQR反馈控制器在不同风况下模拟风力涡轮转速控制的MATLAB.zip

1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

海神之光
评论 10
收藏 已收藏
分享
返回顶部
raistlic
Java SE 62,621 成员 307,251 内容