java如何改变按钮的颜色,不是背景的颜色

2024-10-31 18:41:19
推荐回答(2个)
回答(1):

setForeground() 设置前景/字体颜色
setBackground() 设置背景颜色
具体实现:(假设按钮名称为:button)
设置红字:
button.setForeground(Color.red);
设置黑色背影:
button.setBackground(Color.black);

回答(2):

这是我做的一个改变形状和颜色的Button
package FrameDemo;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonChanged1 extends JButton{
private int x = 200;
private int y = 200;
private int width = 50;
private int height = 50;
private JFrame frm = new JFrame("变化的按钮");
public ButtonChanged1()
{
frm.setVisible(true);
frm.setBounds(300, 200, 500, 500);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.add(this);
setOpaque(false);
setBorderPainted(false);
setContentAreaFilled(false);//取消了button的外框
setFocusable(false);//取消了文字框
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.pink);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.fill(getShape());
super.paintComponent(g);
}
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x,y,width,height);
}
public static void main(String[] args)
{
ButtonChanged1 bChanged1 = new ButtonChanged1();
}
}