Java JTabbedPane Inset Color

孤人 提交于 2019-12-01 06:56:10

You might be able to use UIMangaer Defaults to find the color.

trashgod

You can override paintComponent() to use a GradientPaint in the tab's background, as shown below. A few notes,

  • Let the content adopt the preferred size of it contents, as shown here.

  • Construct the GUI in the event dispatch thread.

  • Use conventional Java names.

Addendum: the elements are not always in the same spot, so I do not know what place to get the color.

It sounds like you want to match a color used internally by the TabbedPaneUI delegate. One approach would be as follows:

  • Render a BufferedImage of the component, as shown here.

  • Determine the coordinates of a Point in top relative to the top of c1.

    Point p = SwingUtilities.convertPoint(c1, 0, -1, top);
    
  • Obtain the color using getRGB(), as shown here; use Zoom to verify the result.

import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

/** @see https://stackoverflow.com/a/16625260/230513 */
public class Main {

    JFrame frame;
    Container c1 = new GradientPanel();
    Container c2 = new GradientPanel();
    JTabbedPane top = new JTabbedPane();

    private static class GradientPanel extends JPanel {

        public GradientPanel() {
            this.add(new JLabel("Here"));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            GradientPaint p = new GradientPaint(0, 0, Color.white,
                getWidth(), getHeight(), Color.gray);
            g2d.setPaint(p);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }
    }

    public void createGUI() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        top = new JTabbedPane(JTabbedPane.TOP);
        top.addTab("1", c1);
        top.addTab("2", c2);
        frame.add(top);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main().createGUI();
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!