package gve.calc.formula;
import java.awt.*;
public class CursorLabel extends Component {
private int cursorPos;
private String text;
private boolean transparent = true;
public CursorLabel(String str) {
this(str,-1);
}
public CursorLabel(String str,int pos) {
text = str;
cursorPos = pos;
}
Negative arguments cause the cursor to disappear. |
public void setCursorPos(int pos) {
cursorPos = pos;
repaint();
}
public void setForeground(Color c) {
transparent = false;
super.setForeground(c);
}
public void setBackground(Color c) {
transparent = false;
super.setBackground(c);
}
public boolean isTransparent() { return transparent; }
public void setTransparent(boolean transp) { transparent = transp; repaint(); }
public int getCursorPos() { return cursorPos; }
public String getText() { return text; }
public void setText(String str) {
text = str;
repaint();
}
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getPreferredSize() {
FontMetrics fm;
try { fm = getFontMetrics(getFont()); }
catch (Exception exc) { return new Dimension(5,5); }
return new Dimension(fm.stringWidth(text) + (cursorPos>=0 ? fm.charWidth(' ') : 0),fm.getHeight());
}
public void paint(Graphics g) {
//try { throw new Error("hehe"); } catch (Error err) { err.printStackTrace(); }
Dimension siz = getSize();
if (!transparent) {
g.setColor(getBackground());
//g.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
//System.out.println("Paint CursorLabel "+text+" with cursor@"+cursorPos+" -> size "+siz+" clip "+g.getClipBounds());
g.fillRect(0,0,siz.width,siz.height);
}
g.setColor(getForeground());
FontMetrics fm = g.getFontMetrics();
int ascent = fm.getAscent();
if (cursorPos < 0) {
g.drawString(text,0,ascent);
return;
}
g.drawString(text.substring(0,cursorPos),0,ascent);
int x = fm.stringWidth(text.substring(0,cursorPos));
int spacewidth = fm.charWidth(' ');
g.fillRect(x,0,spacewidth,fm.getHeight());
//System.out.println("\tPainted "+text.substring(cursorPos)+" @"+(x+spacewidth));
g.drawString(text.substring(cursorPos),x+spacewidth,ascent);
}
public void update(Graphics g) { paint(g); }
protected String paramString() {
return text+","+super.paramString();
}
}