private void addLogoutButtonToTabbedPane(JTabbedPane tabbedPane1) {
final int SPACER = 20;
// resize the button's dimension so that the original tabbed pane's tab's size is intact
final JButton button = new JButton("Logout");
button.setPreferredSize(new Dimension(80, 20));
button.addActionListener((ActionListener) new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
// logout code here
}
});
tabbedPanel.setRequestFocusEnabled(false);
tabbedPanel.addTab(null, null);
tabbedPanel.setEnabledAt(tabbedPanel.getTabCount() - 1, false);
tabbedPanel.setTabComponentAt(tabbedPanel.getTabCount() - 1, button);
tabbedPanel.setUI(new MetalTabbedPaneUI() {
@Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (tabIndex == tabbedPanel.getTabCount() - 1) {
//g.setColor(super.tabAreaBackground);
} else {
super.paintTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
@Override
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (tabIndex == tabbedPanel.getTabCount() - 1) {
// the left border of the last tab should be placed in the position
// of the right border of the tab previous to it because it is blank
int newx = tabbedPanel.getBoundsAt(tabbedPanel.getTabCount() - 2).x +
tabbedPanel.getBoundsAt(tabbedPanel.getTabCount() - 2).width;
g.drawRect(newx, y, 0, h);
} else {
super.paintTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
@Override
protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
// override so that no indicator will be shown in the logout tabbed button
}
@Override
protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { // add -20 to add space from the right
rects[rects.length - 1].x = tabbedPanel.getSize().width - button.getSize().width - SPACER;
button.setLocation(rects[rects.length - 1].x, rects[rects.length - 1].y);
super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
}
});
}