【发布时间】:2022-01-21 19:41:01
【问题描述】:
我有几个 JtextPanes,我想创建一个方法,将变量的值设置为已单击的 TextPane 的名称,因为另一个方法将使用它。还有一个按钮,当用户单击它时添加一个新的 jTextPane,我希望这些新的 TextPanes 继承该方法。或者,如果您知道实现这一目标的更简单方法,我愿意阅读您。如果您需要更多信息或更多代码,请告诉我。
static JTextPane focus;
private void redColorActionPerformed(java.awt.event.ActionEvent evt) { //Ths is the method that works with the focus variable. It changes the color of the text in the clicked textpane.
TextEditor.cambiarColor(new java.awt.Color(255, 0, 0), focus);
}
【问题讨论】:
-
每个 JtextPane 只需要一个鼠标单击事件,通过在事件
focus = (JtextPane)e.getSource();中使用类似这样的内容来更改焦点变量。如果您希望每个 JtextPane 都有该方法,那么我建议扩展 JtextPane 并创建一个内置此功能的自定义 JtextPane。 -
redColorActionPerformed(java.awt.event.ActionEvent evt) - 单击按钮或菜单项时,您似乎正在调用该方法。因此,您应该向组件添加
TextAction。TextAction有一个getFocusedComponent方法,它将返回最后一个具有焦点的文本组件。查看:stackoverflow.com/questions/5668690/… 获取基本示例。 -
被点击的 TextPane 的名称 - 当你点击一个文本组件时,
caret被绘制在组件中,表示你可以在组件中输入。 “光标”是您移动鼠标时绘制的内容。使用适当的术语会产生更好的答案。
标签: java swing listener jtextpane mouseclick-event