如何在BasicTabbedPaneUI的paintTab()方法中获取标签文本与选中标签索引
解决JTabbedPane自定义UI中获取选中标签索引与标签文本的问题
在自定义BasicTabbedPaneUI时,你可以通过以下方式获取所需的选中状态和标签文本:
关键实现要点
- 获取选中标签索引:
BasicTabbedPaneUI内部有一个受保护的成员变量tabPane,它指向当前关联的JTabbedPane实例,直接调用tabPane.getSelectedIndex()就能拿到选中标签的索引。 - 获取标签文本:通过
tabPane.getTitleAt(tabIndex)方法,传入当前绘制的tabIndex参数,即可获取对应标签的标题文本。
修改后的完整代码示例
private static class myTabbedPaneUI extends BasicTabbedPaneUI { @Override protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { Graphics2D g2d = (Graphics2D) g; // 判断当前标签是否为选中状态,执行对应绘制逻辑 if (tabIndex == tabPane.getSelectedIndex()) { drawSelected(g2d, rects[tabIndex]); } else { drawUnselected(g2d, rects[tabIndex]); } // 获取并绘制标签文本 String tabText = tabPane.getTitleAt(tabIndex); if (tabText != null && !tabText.isEmpty()) { // 利用FontMetrics计算文本居中位置,确保显示在标签合理区域 FontMetrics metrics = g2d.getFontMetrics(); int textX = textRect.x + (textRect.width - metrics.stringWidth(tabText)) / 2; int textY = textRect.y + (textRect.height + metrics.getAscent()) / 2; g2d.setColor(Color.BLACK); g2d.drawString(tabText, textX, textY); } } // 自定义选中标签的绘制逻辑 private void drawSelected(Graphics2D g2d, Rectangle tabRect) { g2d.setColor(Color.PINK); g2d.fillRoundRect(tabRect.x, tabRect.y, tabRect.width, tabRect.height + 20, 6, 6); g2d.setColor(Color.BLUE); g2d.drawRoundRect(tabRect.x, tabRect.y, tabRect.width, tabRect.height + 20, 6, 6); } // 自定义未选中标签的绘制逻辑 private void drawUnselected(Graphics2D g2d, Rectangle tabRect) { // 可根据需求修改未选中样式,示例为灰色填充+黑色边框 g2d.setColor(Color.LIGHT_GRAY); g2d.fillRoundRect(tabRect.x, tabRect.y, tabRect.width, tabRect.height + 20, 6, 6); g2d.setColor(Color.BLACK); g2d.drawRoundRect(tabRect.x, tabRect.y, tabRect.width, tabRect.height + 20, 6, 6); } }
补充说明
tabPane是BasicTabbedPaneUI的受保护成员变量,子类可直接访问,无需额外初始化。- 绘制文本时结合
textRect和FontMetrics计算位置,能避免文本偏移或超出标签边界的问题。
内容的提问来源于stack exchange,提问作者mg3
相关产品推荐
相关产品推荐

