Share the post "Create A Logout Button Beside A JTabbedPane"
![]()
Creating a logout button beside a set of tabbed panes in a JTabbedPane like the image pictured above can only be done by adding another tabbed pane and overriding the pane’s UI methods to remove the borders of the last tabbed pane while setting the location of the logout button to the far right.
If you do not override the UI methods of the JTabbedPane, the tabbed pane’s borders will always be visible plus the logout button will always be positioned next to the other tabbed panes instead of to the far right.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
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); } }); } |