How do I select text from a string using the mouse when it's rendering in Graphics?
Hey, I'm developing UI Controls for software I'm making in JAVA. I'm rendering everything using Graphics/Graphics2D and I need a little assistance with a problem I've come across. I have the textbox control all set up so you can type, and backspace text. The next problem I have is being able to select portions of this text. I'm not exactly sure where I should start on this matter. Be low I will post at my controls render code and it's typing code.
@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;
}
}
}
How do I select text from a string using the mouse when it's rendering in Graphics?
Add a MouseListener
and when it fires, check if it within the bounds of the String
.
Ways to check the bounds of a String
: