2011-11-19 159 views
1

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

这种方法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); 

结果: enter image description here

试过设置setOpaque(真)也。但是你可以看到account_btn的结果,即“Accounting”。 setOpaque似乎没有效果。

任何想法。

SOLUTION:

设定为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。还需要在初始阶段更新我的动态添加的面板,然后不需要再设置任何东西。

+1

什么PLAF?你的[SSCCE](http://sscce.org/)在哪里? –

+0

我不确定编辑您的问题是否是为了解决我的意见。如果是这样,你似乎错过了我的观点。 –

回答

3

Red Buttons

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?

+0

Andrew,我正在使用NetBeans并没有设置任何PLAF。在搜索文件中找不到任何此类文件。我是否缺少要搜索的位置? – Tvd

+0

*“我是否缺少搜索位置?”*我应该怎么知道,我不使用Netbeans。在IDE中发布的代码的确切行为是什么? –

+1

@Tvd:在NetBeans中,只需查看它生成的GUI代码即可。在源代码视图中,搜索LookAndFeel,并且您可能会发现需要的所有信息才能让Andrew更好地帮助您。 1+给安德鲁他(总是)有用的建议,并祝贺打破20K障碍。 –

1

尝试设置边界涂上假的和不透明的真实

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

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