【发布时间】:2020-07-11 06:42:59
【问题描述】:
我创建了一个四舍五入的JTextField,它覆盖了paintComponent(g: Graphics) 方法。形状和文本正确绘制,但我没有实现任何显示光标的东西。
我怎样才能做到这一点?
编辑: super.paintComponent(...) 不是解决方案。如果我使用它,那么您可以看到另一个绘制组件的边缘。
这是目前为止的代码(没有描述任何渲染光标的内容!)
@Override
protected void paintComponent(Graphics g) {
//TODO entfernen
//super.paintComponent(g);
if(g instanceof Graphics2D) {
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draw button background
graphics.setColor(getBackground());
graphics.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, arcRadius, arcRadius);
this.paintText(graphics);
}
}
protected final void paintText(@NotNull Graphics2D g) {
//Draw font
g.setColor(getForeground());
if (this.getFont() != null && this.getText() != null) {
FontMetrics fm = getFontMetrics(getFont());
g.setColor(this.getForeground());
g.drawString(this.getText(), ((this.getWidth() / 2) - (fm.stringWidth(this.getText()) / 2)),
((this.getHeight() / 2) + fm.getMaxDescent()));
}
}
编辑 2: 这是结果,当我调用 super.paintComponent(...) 时:
如您所见,超级组件是可见的。这就是为什么,我不调用 super 方法。
有人有使用 Carets 的经验吗?很确定这是正确的方法......
【问题讨论】:
-
我怀疑你没有调用 super.paintComponent(g) 作为你的 paintComponent 方法的第一行。否则,是时候在 Javadoc 中搜索 JTextField。
-
您是否希望有人发布完整的代码解决方案,说明如何创建圆角
JTextField,或者您需要帮助来纠正您的代码?如果是后者,那么我建议您edit您的问题并发布您的代码。如果是前者,那我怀疑这会发生。 -
@GilbertLeBlanc:你猜对了。事实上它已经被注释掉了
-
调用 super 是错误的!绘制了第二个按钮,该按钮显示在自定义按钮的圆角中。
-
也许以下会有帮助? Painting in AWT and Swing 和 Performing Custom Painting
标签: java swing jtextfield caret