簡體   English   中英

擴展Swing應用程序中的系統外觀

[英]Extend the system look and feel in a Swing application

我想為Swing應用程序使用系統外觀。 因此,我使用了getSystemLookAndFeelClassName()方法,該方法效果很好。

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

但是,現在我想改變這一切的JButtons應用程序的(在我所有的JFramesJDialogsJOptionPanesJFileChoosers等),只有JButtons 因此,我想知道如何擴展系統的外觀,以保持除JButtons (以及我想要的灰色背景的JPanels之外的所有組件的外觀。

謝謝。

最后,我擴展了系統外觀,如下所示:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("ButtonUI", "com.my.package.MyButtonUI");
UIManager.put("Panel.background", Color.green);

使用MyButtonUI

public class MyButtonUI extends BasicButtonUI {

    public static final int BUTTON_HEIGHT = 24;

    private static final MyButtonUI INSTANCE = new MyButtonUI ();

    public static ComponentUI createUI(JComponent b) {
        return INSTANCE;
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        AbstractButton button = (AbstractButton) c;
        Graphics2D g2d = (Graphics2D) g;
        final int buttonWidth = button.getWidth();
        if (button.getModel().isRollover()) {
            // Rollover
            GradientPaint gp = new GradientPaint(0, 0, Color.green, 0, BUTTON_HEIGHT * 0.6f, Color.red, true);
            g2d.setPaint(gp);
        } else if (button.isEnabled()) {
            // Enabled
            GradientPaint gp = new GradientPaint(0, 0, Color.red, 0, BUTTON_HEIGHT * 0.6f, Color.gray, true);
            g2d.setPaint(gp);
        } else {
            // Disabled
            GradientPaint gp = new GradientPaint(0, 0, Color.black, 0, BUTTON_HEIGHT * 0.6f, Color.blue, true);
            g2d.setPaint(gp);
        }
        g2d.fillRect(0, 0, buttonWidth, BUTTON_HEIGHT);
        super.paint(g, button);
    }

    @Override
    public void update(Graphics g, JComponent c) {
        AbstractButton button = (AbstractButton) c;
        if (isInToolBar(button)) {
            // Toolbar button
            button.setOpaque(false);
            super.paint(g, button);
        } else if (button.isOpaque()) {
            // Other opaque button
            button.setRolloverEnabled(true);
            button.setForeground(Color.white);
            paint(g, button);
        } else {
            // Other non-opaque button
            super.paint(g, button);
        }
    }

    private boolean isInToolBar(AbstractButton button) {
        return SwingUtilities.getAncestorOfClass(JToolBar.class, button) != null;
    }
}

注意:我強烈推薦此鏈接: http : //tips4java.wordpress.com/2008/10/09/uimanager-defaults/ (來自Robin)

謝謝。

您還可以創建自己的按鈕類,例如CustomButton,它擴展了JButton,進行所有更改並使用它代替標准JButton。 這樣,您可以同時使用自定義按鈕和標准按鈕-如果您改變主意並想在某個地方添加標准JButton;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM