使用 Graphics/Graphics2D 选择文本
在图形中渲染时如何使用鼠标从字符串中选择文本?
嘿,我正在为我用 JAVA 制作的软件开发 UI 控件。我正在使用 Graphics/Graphics2D 渲染所有内容,我需要一些帮助来解决我遇到的问题。我已经设置了文本框控件,以便您可以键入和退格文本。我遇到的下一个问题是能够选择此文本的部分内容。我不确定我应该从哪里开始处理这个问题。低一点,我将在我的控件渲染代码上发布它正在输入代码。
渲染代码
@Override
public void render(Graphics g) {
// Draw Fill
Graphics2D g2 = (Graphics2D) g.create();
if (isActive) {
g2.setPaint(new GradientPaint(new Point(x, y), Colors.textboxActiveTop, new Point(x, y + h), Colors.textboxActiveBottom));
} else {
g2.setPaint(new GradientPaint(new Point(x, y), Colors.textboxTop, new Point(x, y + h), Colors.textboxBottom));
}
g2.fillRect(x, y, w, h);
// Draw Text
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (isPassword) {
int count = text.toString().length();
for (int i = 0; i < text.toString().length(); i++) {
g2.setColor(Colors.white50percent);
g2.fillArc(x + (w / 2) + (i * 5) - ((count * 5) / 2), y + (h / 2), 4, 4, 0, 360);
g2.setColor(foreColor);
g2.fillArc(x + (w / 2) + (i * 5) - ((count * 5) / 2), y + (h / 2) - 1, 4, 4, 0, 360);
}
} else {
if (isCentered) {
g2.setColor(Colors.white50percent);
g2.drawString(text.toString(), x + (w / 2) - (g.getFontMetrics().stringWidth(text.toString()) / 2), y + (h / 2) + (g.getFontMetrics().getMaxAscent() / 2) + 1);
g2.setColor(foreColor);
g2.drawString(text.toString(), x + (w / 2) - (g.getFontMetrics().stringWidth(text.toString()) / 2), y + (h / 2) + (g.getFontMetrics().getMaxAscent() / 2));
} else {
g2.setColor(Colors.white50percent);
g2.drawString(text.toString(), x + 5, y + (h / 2) + (g.getFontMetrics().getMaxAscent() / 2) + 1);
g2.setColor(foreColor);
g2.drawString(text.toString(), x + 5, y + (h / 2) + (g.getFontMetrics().getMaxAscent() / 2));
}
}
// Draw Border
g.setColor(Colors.borderColor);
g.drawRect(x, y, w, h);
// Draw Hightlights
g.setColor(Colors.white50percent);
g.drawRect(x + 1, y + 1, w - 2, h - 2);
g.drawRect(x - 1, y - 1, w + 2, h + 2);
}
键入代码
@Override
public void keyTyped(KeyEvent e) {
int code = (int) e.getKeyChar();
if (isActive) {
if (code == 8) {
if (text.toString().length() >= 1) {
text = text.toString().substring(0, text.toString().length() - 1);
}
} else {
String character = "" + (char)code;
if(acceptedCharacters.contains(character.toLowerCase()))
text = text.toString() + (char) code;
}
}
}