How to set a background color of a JButton in Java?

后端 未结 6 1552
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 19:33

I am developing a Java Desktop Application. In it I have 4 JButtons on a JPanel. Now I want that whenever a button is clicked its background color

6条回答
  •  温柔的废话
    2021-01-18 20:27

    If you wish you can redesign your whole button UI

    public class buttonUI extends javax.swing.plaf.basic.BasicButtonUI{
    
    buttonUI(JButton b){
        b.setContentAreaFilled(false);
    }
    
    @Override
        public void paint(Graphics g,JComponent c){
                 Graphics2D g2d = (Graphics2D) g;
                 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                 AbstractButton b = (AbstractButton) c;
                 g2d.setFont(font.deriveFont(11f));
                 Dimension d = b.getSize();
                 FontMetrics fm = g2d.getFontMetrics();
                 g2d.setColor(new Color(100,100,100));
                 String caption = b.getText();
                 int x = (d.width - fm.stringWidth(caption)) / 2;
                 int y = (d.height + fm.getAscent()) / 2 - 2;
                 g2d.drawString(caption, x, y);        
            }   }
    

    and in your main piece of code use like

    jButton1.setUI(new buttonUI(jButton1));
    

    This how I use it .. you can have your own way too

提交回复
热议问题