為 List、Menu 等列表組件提供可復用、支持邊框、漸變色、圓角矩形的選擇高亮條組件。
// 抽象基類
public abstract class Select {
protected boolean isBorder = false;
protected int selectColor = 0x676767; // 默認高亮色
// 核心繪製方法,子類實現具體風格
public abstract void paint(int x, int y, int width, int height, Graphics g);
}
// 具體實現:漸變選擇條
public class ShadeSelect extends Select {
private Border border; // 邊框對象
public ShadeSelect(int color, boolean hasBorder) {
this(color, hasBorder, hasBorder ? Border.getRectBorder() : null);
}
public ShadeSelect(int color, boolean hasBorder, Border border) {
if (hasBorder && border == null) throw new IllegalArgumentException("Border required");
this.selectColor = color;
this.isBorder = hasBorder;
this.border = border;
}
public void paint(int x, int y, int width, int height, Graphics g) {
if (isBorder) {
border.paint(x, y, width, height, g); // 先畫邊框
int bw = border.getBorderWidth();
x += bw; y += bw;
width -= 2*bw; height -= 2*bw;
}
// 根據邊框類型選擇漸變繪製策略
if (border instanceof RoundRectBorder) {
paintShadeRoundRect(x, y, width, height, g);
} else {
paintShadeRect(x, y, width, height, g);
}
}
// 矩形漸變:按寬度遍歷垂直線,顏色逐漸變淺
private void paintShadeRect(int x, int y, int w, int h, Graphics g) {
for (int i = 0; i <= w; i++) {
g.setColor(selectColor + i/2); // 簡單線性漸變
g.drawLine(x + i, y, x + i, y + h);
}
}
// 圓角矩形漸變:繪製同心圓角矩形,顏色逐漸變淺
private void paintShadeRoundRect(int x, int y, int w, int h, Graphics g) {
for (int i = 1; i <= w/2; i++) {
g.setColor(selectColor + i/2);
g.drawRoundRect(x + i, y, w - i, h, 6, 6); // 固定圓角半徑 6
g.drawRoundRect(x + w - i, y, i, h, 6, 6);
}
g.setColor(selectColor);
g.drawRoundRect(x, y, w/2, h, 6, 6);
g.drawRoundRect(x + w/2, y, w/2, h, 6, 6);
}
}
Select 定義契約,ShadeSelect 實現漸變,未來可擴展 GlossySelect、ImageSelect 等。Border 接口 (RoundRectBorder、RectBorder),選擇條不關心邊框細節。Graphics.drawRoundRect 硬件加速 (如有)。// List 自定義渲染 (需繼承 List 並重寫 paint 或使用自定義 CellRenderer)
List list = new List("選單", List.IMPLICIT) {
private Select selector = new ShadeSelect(0x0000FF, true); // 藍色漸變+邊框
protected void paintCell(Graphics g, int index, int x, int y, int w, int h) {
if (isSelected(index)) selector.paint(x, y, w, h, g);
// 繪製文本/圖標...
}
};
通過 Select 抽象層 + ShadeSelect 漸變實現 + Border 解耦,構建了可配置、可復用、視覺效果優於默認高亮的選擇條組件,為 J2ME 輕量級 UI 庫奠定基礎。