gpt4 book ai didi

java - 如何为JButton设置自定义渐变?

转载 作者:行者123 更新时间:2023-12-02 00:11:27 24 4
gpt4 key购买 nike

我想做类似 this 的事情,但仅为我需要的一两个按钮设置自定义渐变,而不是为所有 JButton 实例设置自定义渐变。并动态设置/取消设置它 - 类似于按钮选择/取消选择模式。

最佳答案

所以,这就是答案。

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

class JGradientButton extends JButton{
Color color1 = Color.WHITE;
Color color2 = Color.PINK;
JGradientButton(){
super("Gradient Button");
setContentAreaFilled(false);
setFocusPainted(false); // used for demonstration
addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent evt) {
color2 = (color2==Color.PINK) ? Color.GREEN : Color.PINK;
//System.out.println(button.isSelected());
}
});

}

@Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(new GradientPaint(
new Point(0, 0),
color1,
new Point(0, getHeight()),
color2));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();

super.paintComponent(g);
}


}

还有...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public final class JGradientButtonDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI(){
final JFrame frame = new JFrame("Gradient JButton Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
frame.add(new JGradientButton());
frame.setSize(new Dimension(300, 150)); // used for demonstration
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}


}

关于java - 如何为JButton设置自定义渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12749362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com