有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JButton背景图像

我写了一个POS系统(销售点)的乐趣。POS系统的一个典型特征是按钮对于不同的产品具有不同的背景颜色。但我不是说按钮图片背后的背景,我是说,就像我从谷歌图片上得到的这张随机图片: enter image description here

编辑:注意,我将外观更改为system one

我需要用我的纽扣做些类似的事情。我知道有几种方法可以做到这一点:

  1. 为我的按钮创建外观和感觉
  2. 在我的JButtons中完全覆盖paintComponenet方法(但这是一种非常可怜的方法…当我覆盖它时,边框+文本没有绘制出来…显然是个坏主意)
  3. 使用按钮。setContentAreaFilled(假);,然后在按钮后面放一个与按钮大小相同的JPanel

我真的不知道如何创建自己的外观,这听起来很痛苦,尤其是对于一个按钮,我听到一些关于打破外观的声音,这让我害怕放弃这个想法。第三种方法听起来似乎有道理,也不是很难,但我想知道,做我想做的事情的最佳方法是什么

现在,我创建Buton的代码如下:

JButton b = new JButton(text);
    b.addActionListener(this);
    b.setFont(Main.f);
    b.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttons.add(b);
    return b;

我把这段代码弄乱了(主要是为了好玩,不是为了实用):

JButton b = new JButton(text){
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Color bg = getBackground();
            int borderchange = -50;
            g.setColor(new Color(
                    Math.max(0,bg.getRed()+borderchange),
                    Math.max(bg.getGreen()+borderchange,0),
                    Math.max(bg.getBlue()+borderchange,0)));
            g.fillRect(0,0,getWidth(),getHeight());
            g.setColor(getBackground());
            int border = 4;
            g.fillRect(border,border,getWidth()-border,getHeight()-border);
            g.setColor(Color.BLACK);
            g.setFont(getFont());
            g.drawString(getText(),getWidth()/2,getHeight()/2);
        }
    };

共 (2) 个答案

  1. # 1 楼答案

    • Creating a look and feel for my buttons?

      1. 外观和感觉就像主题一样,

      2. 默认情况下,此配色方案有一、二、三种颜色,此主题适用于所有Swing JComponents,

      3. 那么所有Swing JC组件都有相同的颜色,配色方案

      4. 不是你想要的东西

    • Completely overriding the paintComponenet method in my JButtons(But that's a pretty pathetic way to do it... and the border + text isn't drawn when I override that... obviously a bad idea)

      1. JButton有多种颜色

      2. 你可以用一种颜色(不是你想要的颜色)覆盖paintComponent、填充整个区域、矩形或使用GradientPaint

      3. 您可以选择覆盖BasicButtonUI

      4. 覆盖UIManager and put there arrays of Colors中的正确键

    • Using button.setContentAreaFilled(false);, and putting a JPanel of the same size as the button behind the button.

      1. 这可能是最简单的方法,准备图标(或下载一组图标)

      2. 使用正确的方法,实现(鼠标、键和键绑定)事件

  2. # 2 楼答案

    你试过:

    yourButton.setBackground(COLOR)
    

    ?