簡體   English   中英

如何填充 jbutton

[英]How to Fill jbutton

我想填充一個 jbutton,我在網上找到的所有內容都在改變背景和前景色,這不是我想要的。

public GameOfLife () {
    frame = new JFrame("2 player Game of Life");
    frame.setSize(505, 533);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);

    buttons = new JButton[10][10];

    for (int i = 0; i < buttons.length; i++) {
        for (int j = 0; j < buttons[i].length; j++) {
           buttons[i][j] = new JButton();

            buttons[i][j].setBounds(i*50+2, j*50+2, 50, 50);
            frame.add(buttons[i][j]);
            buttons[i][j].addActionListener(this);
            //buttons[i][j].setBackground(Color.black);
            buttons[i][j].setForeground(Color.BLUE);
            buttons[i][j].setOpaque(true);

        }
    }

    frame.setLayout(null);
    frame.setVisible(true);


}

setBackground 僅更改按鈕背面的內容,setForeground 僅更改按鈕中文本的顏色(如果有的話)。 這里的按鈕總是白色的

GUI 的屏幕截圖。這里

所以我不想改變背景顏色(這里是紅色和藍色),而是想改變按鈕的填充(這里是白色)。 有辦法嗎?

這是一個可編譯的示例,它使用圖標來更改面部。

import javax.swing.*;
import java.awt.image.*;
import java.awt.*;
public class Icony{
    static JButton make(Color r){
        BufferedImage img = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
        Graphics g = img.getGraphics();
        g.setColor(r);
        g.fillRect(0, 0, 64, 64);
        g.dispose();
        JButton button = new JButton();
        button.setOpaque(false);
        button.setBackground( Color.RED);
        button.setIcon( new ImageIcon(img) );
        return button;
    }
    public static void main(String[] args){
        JFrame frame = new JFrame("button");
        JPanel panel = new JPanel(new GridLayout(2,2));
        panel.add(make(Color.RED));
        panel.add(make(Color.BLUE));
        panel.add(make(Color.GREEN));
        panel.add(make(Color.YELLOW));
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

暫無
暫無

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

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