繁体   English   中英

摇摆:设置JButton的背景

[英]Swing : Setting JButton's background

我想设置JButton的背景色。 为此,我使用setBackground()方法。

此方法jsut设置按钮的边框颜色,而不是指定颜色的整个按钮。 为什么这样 ? 这是设置按钮背景色的唯一方法。 由于仅设置指定颜色的按钮的边框而不是实际按钮的边框,我在哪里出错?

代码:

    account_btn.setAction(actionMap.get("AccountingClicked")); // NOI18N
    account_btn.setBackground(Utility.getBackgroundColor());
    account_btn.setFont(Utility.getButtonFont());
    account_btn.setForeground(Utility.getTextColor());
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cashaccountingapp.CashAccountingApp.class).getContext().getResourceMap(MainPanel.class);
    account_btn.setText(resourceMap.getString("account_btn.text")); // NOI18N
    account_btn.setBorderPainted(false);
    account_btn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    account_btn.setName("account_btn"); // NOI18N
    account_btn.setOpaque(true);
    add(account_btn);

结果: 在此处输入图片说明

也尝试过设置setOpaque(true)。 但是您可以看到account_btn的结果,即“ Accounting”。 setOpaque似乎没有作用。

任何想法。

解决方案:

设置L&F

    private void initLookandFeel() {
    try {
        System.out.println("DEFAULT Look & Feel = " + UIManager.getLookAndFeelDefaults().toString());
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        javax.swing.SwingUtilities.updateComponentTreeUI(this.mainPanel);
        System.out.println("Look & Feel = " + UIManager.getLookAndFeel().toString());
    } catch(Exception e) { ..... }
    }

我在initComponents()之后调用initLookandFeel()并更新我的mainPanel。 还需要在初始阶段更新我动态添加的面板,然后无需进行其他设置。

红色按钮

import java.awt.*;
import javax.swing.*;

class ColoredButtons {

    ColoredButtons() {
        JPanel gui = new JPanel(new GridLayout(1,0,5,5));

        JButton one = new JButton("One");
        one.setBackground(Color.RED);
        JButton two = new JButton("Two");
        two.setBackground(Color.RED);

        gui.add(one);
        gui.add(two);

        JOptionPane.showMessageDialog(null, gui);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ColoredButtons();
            }
        });
    }
}

有我的SSCCE。 这些按钮是红色的。 PLAF是金属。

这使我回到:SSCCE在哪里? 您正在使用什么PLAF?

尝试将边框设置为false和opaque true

account_btn.setBorderPainted(false);
account_btn.setOpaque(true);

我相信Jbutton背景是由您使用的特定外观控制的。 要更改背景,您可能需要修改

setUI(ComponentUI newUI)

与你自己的一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM