I'm trying to draw a border over a Text in SWT...
This is what I got for now:
public class BorderedText extends Text {
public BorderedText(Composite parent, int style) {
super(parent, style);
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setAntialias(SWT.ON);
if (isFocusControl()) {
Color color = new Color(getDisplay(), new RGB(82, 168, 236));
e.gc.setAlpha(200);
e.gc.setForeground(color);
Rectangle rect = new Rectangle(0,0, getClientArea().width-1, getClientArea().height-1);
Transform t = new Transform(getDisplay());
e.gc.setTransform(t);
e.gc.drawRoundRectangle(0, 0, rect.width, rect.height, 4,4);
} else {
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
Rectangle rect = new Rectangle(0,0, getClientArea().width-1, getClientArea().height-1);
e.gc.drawRectangle(rect);
}
}
});
When the component receive focus, he is like this

But when I type something, he got screwed up

What am I missing?
EDIT
I gave up on Text and done it with StyledText
public class BorderedText extends StyledText {
public BorderedText(Composite parent) {
super(parent, SWT.WRAP);
setTabStops(new int[] {0});
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setAntialias(SWT.ON);
if(isFocusControl()){
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION));
e.gc.drawRoundRectangle(0, 0, getClientArea().width-1, getClientArea().height-1, 6,6);
} else {
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
e.gc.drawRoundRectangle(0, 0, getClientArea().width-1, getClientArea().height-1, 6,6);
}
}
});
addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
redraw();
}
@Override
public void focusGained(FocusEvent e) {
redraw();
}
});
addControlListener(new ControlListener() {
@Override
public void controlResized(ControlEvent e) {
redraw();
}
@Override
public void controlMoved(ControlEvent e) {
redraw();
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.character == SWT.TAB){
e.doit = false;
traverse(SWT.TRAVERSE_TAB_NEXT);
}
}
});
}
@Override
protected void checkSubclass() {
//
}
@Override
protected void checkWidget() {
//
}
You have two possibilities:
You can create a new Text widget with SWT.BORDER as a style argument. This would give you a nice looking border.
You can use the StyledText widget. The StyledText widget enables you to define margins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With