首页 > 解决方案 > 用Java制作多色按钮

问题描述

我想在我的 Java Swing GUI 中创建一个正方形网格。我需要切换它们的状态,所以我认为 JToggleButton 适合每个方块。

我遇到的问题是我想根据给定的百分比对每个切换按钮进行部分着色。例如,如果 50% 和 50% 我希望按钮的左半部分为绿色,而右半部分为红色。如果 25%,25%,50% 我需要 3 种颜色。我还需要使用按钮文本字段,因此解决方案中不允许隐藏。可以用 JToggleButton 做这样的事情吗?有没有更好的元素可以使用?或者我该怎么做?

我很抱歉到目前为止没有发布我的作品,但我找不到任何与此类事情的例子相近的东西。

我想得到这样的结果,每个方块都是一个按钮。 在此处输入图像描述

标签: javaswingjtogglebutton

解决方案


您可以根据需要通过覆盖构建一个具有可变 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 种颜色切换按钮)


在此处输入图像描述


推荐阅读