java - 用Java制作多色按钮
问题描述
我想在我的 Java Swing GUI 中创建一个正方形网格。我需要切换它们的状态,所以我认为 JToggleButton 适合每个方块。
我遇到的问题是我想根据给定的百分比对每个切换按钮进行部分着色。例如,如果 50% 和 50% 我希望按钮的左半部分为绿色,而右半部分为红色。如果 25%,25%,50% 我需要 3 种颜色。我还需要使用按钮文本字段,因此解决方案中不允许隐藏。可以用 JToggleButton 做这样的事情吗?有没有更好的元素可以使用?或者我该怎么做?
我很抱歉到目前为止没有发布我的作品,但我找不到任何与此类事情的例子相近的东西。
解决方案
您可以根据需要通过覆盖构建一个具有可变 2 色背景的按钮
paintComponent
:
import java.awt.*;
import javax.swing.*;
public class TwoColorsButton extends JButton{
private final Color leftColor, rightColor;
private int percentOfLeftColor;
public TwoColorsButton(String text) {
this(text,Color.RED, Color.GREEN, 50);
}
public TwoColorsButton(String text, Color leftColor,Color rightColor, int percentOfLeftColor) {
super(text);
this.leftColor = leftColor;
this.rightColor = rightColor;
this.percentOfLeftColor = percentOfLeftColor;
//make button transparent
setOpaque(false);
setContentAreaFilled(false);
setBorderPainted(false);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
int leftWidth = getWidth() * percentOfLeftColor/100;
g2.setColor(leftColor);
g2.fillRect(0, 0, leftWidth , getHeight());
g2.setColor(rightColor);
g2.fillRect(leftWidth, 0, getWidth() -leftWidth, getHeight());
g2.setPaint(Color.BLACK);
super.paintComponent(g2); //button is transparent so super paints text only
g2.dispose();
}
public void setPercentOfLeftColor(int percentOfLeftColor) {
this.percentOfLeftColor = percentOfLeftColor;
repaint();
}
public int getPercentOfLeftColor() {
return percentOfLeftColor;
}
public static void main(String[] args) {
//run button test
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel topPanel = new JPanel();
TwoColorsButton twoColorBtn = new TwoColorsButton("Some Text");
topPanel.add(twoColorBtn);
frame.add(topPanel, BorderLayout.PAGE_START);
JPanel bottomPanel = new JPanel();
JButton runTestBtn = new JButton("Run test");
runTestBtn.addActionListener(e->{
runTestBtn.setEnabled(false);
new Timer(1000, e1 ->{
int percent = twoColorBtn.getPercentOfLeftColor() +25;
percent = percent > 100 ? 0 : percent;
twoColorBtn.setPercentOfLeftColor(percent);
}).start();
});
bottomPanel.add(runTestBtn);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
如果需要,可以轻松修改代码以允许 3 种颜色。(在这里
在线测试) (在这里
查看基本的 3 种颜色切换按钮)
推荐阅读
- r - 从非结构化日期搜索中排除错误匹配 - R
- javascript - 如何从 openstreet 地图中释放内存
- python - 自制分散函数,如果可用,内置函数给出 ax1 和 ax2
- amazon-ecs - 设置 Pact 代理的基本 url
- r - R语言使用 as.Date 后结果将是 NA 或不同
- dns - Terraform:Route53、LB 和 CDN 相互依赖
- android - layout_constraintWidth_default="wrap" 是否已弃用任何替代方案?
- c# - 为什么修改本地数据时yield return不起作用?
- javascript - 如何仅在给定其 cognito 子用户和具有完全 AWS 权限的安全服务器(安全后端服务器到服务器身份验证)的情况下对 cognito 用户进行身份验证
- javascript - JavaScript:异步创建实例并在不同模块中使用