简体   繁体   English

如何在JButton边框内适应ImageIcon

[英]How to fit ImageIcon within JButton borders

I want to color some JButtons, some other questions here showed me, that it would be easier to paint a little image (did it with gimp) and set it as icon for the JButton. 我想为一些JButton着色,这里有一些其他问题告诉我,绘制一个小图像(用gimp做它)会更容易,并将它设置为JButton的图标。

The number and size of the buttons should be variable (they're in a grid), so I want a high res image that I can scale how i need it. 按钮的数量和大小应该是可变的(它们在网格中),所以我想要一个高分辨率图像,我可以扩展我需要它的方式。

The problem now is, I don't know how to 'cut the edges' of the icon, because the buttons have rounded edges. 现在的问题是,我不知道如何“切割图标的边缘”,因为按钮有圆角。

Pic不在按钮的边框内

Here you can see that the image is not inside of the button border. 在这里,您可以看到图像不在按钮边框内。

And here is my method in the class that extends JButton. 这是我在类中扩展JButton的方法。

public void setYellow() {
    URL u = getClass().getResource("/img/yellow.png");
    ImageIcon i = new javax.swing.ImageIcon(u);
    //Image img = i.getImage();
    //img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH); 
    //i = new ImageIcon(img);
    setIcon(i);
}

EDIT 编辑

package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import control.Control;
import view.Field;
import view.View;

public class HelloWorldSwing {

  /**
     * @param args
     */
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TestView.initialize();
            }
        });
    }    

}

class TestView {
private static TestView view = new TestView();
public static TestView getView() {
    return view;
}

private TestView() {
    JFrame frame = new JFrame("HelloWorldSwing");
    frame.setLayout(new GridLayout(0,3));
    int buttonSize = 40;

    frame.getContentPane().add(new MyButton(buttonSize));
    frame.getContentPane().add(new MyButton(buttonSize));
    frame.getContentPane().add(new MyButton(buttonSize));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

public static void initialize() {
}
}

class MyButton extends JButton {

int size;
public MyButton(int size) {
    this.size = size;
    setPreferredSize(new Dimension(size, size));
    this.addActionListener(new ButtonHandler());
    setBorder(LineBorder.createGrayLineBorder());
    setOpaque(true);
}

public void setYellow() {
    //URL u = getClass().getResource("/img/test.png"); // 64x64 png pic
        URL u1 = null;
    try {
        u1 = new URL("http://assets1.qypecdn.net/uploads/users/0195/7210" 
                       + "/calvin_yellow_original_thumb.jpg");         
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ImageIcon i = new javax.swing.ImageIcon(u1);
//      Image img = i.getImage();
//      img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH); 
//      i = new ImageIcon(img);
    setIcon(i);
//      setBorderPainted(false);
//      setContentAreaFilled(false); did not help
}
}

class ButtonHandler implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
    MyButton mb = (MyButton) e.getSource();
    mb.setYellow();
}
}

EDIT 2 编辑2

Here are the pictures where the lines in setYellow() 这里是setYellow()中的行的图片

setBorderPainted(false);
setContentAreaFilled(false);

are not commented out (unfortunately there is no difference) 没有注释掉(遗憾的是没有区别)

Before button is clicked: 单击按钮之前:

在此输入图像描述

After button is clicked: 单击按钮后:

在此输入图像描述

UPDATE UPDATE

I added Borders to the MyButton constructor 我将Borders添加到MyButton构造函数中

setBorder(LineBorder.createGrayLineBorder());

and now the icons are inside the button borders. 现在图标在按钮边框内。 I added pictures. 我添加了图片。

在此输入图像描述

在此输入图像描述

But as you can see, we don't have these rounded button edges anymore. 但正如您所看到的,我们不再具有这些圆形按钮边缘。

button.setBorderPainted(false);
button.setContentAreaFilled(false);

As seen in this answer . 正如这个答案所见。

Update 更新

I do not quite get what you are trying to achieve if not this. 如果不是这样的话,我不会得到你想要达到的目标。

12个黄色按钮带橙色翻转图标

I made the rollover icon to be orange so that we could easily see the size of one button, but otherwise I put 4 in a row to ensure the minimum frame width did not insert extra space between the buttons in a row. 我将翻转图标设为橙色,这样我们就可以轻松看到一个按钮的大小,但是我连续放了4个,以确保最小的框架宽度没有在一行按钮之间插入额外的空间。

import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class HelloWorldSwing {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TestView.getView();
            }
        });
    }    
}

class TestView {

    private static TestView view = new TestView();

    public static TestView getView() {
        return view;
    }

    private TestView() {
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setLayout(new GridLayout(3,4));
        int buttonSize = 40;

        for (int i=0; i<12; i++) {
            frame.getContentPane().add(new MyButton(buttonSize));
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void initialize() {
    }
}

class MyButton extends JButton {

    int size;

    public MyButton(int size) {
        this.size = size;
        setPreferredSize(new Dimension(size, size));
        this.addActionListener(new ButtonHandler());
        setOpaque(true);
        setYellow();
    }

    public Image getImage(int sz, Color color) {
        BufferedImage bi = new BufferedImage(sz,sz,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setColor(color);
        g.fillRect(0, 0, sz, sz);

        g.dispose();
        return bi; 
    }

    public void setYellow() {
        Image img = getImage(64, Color.YELLOW).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH); 
        setIcon(new ImageIcon(img));
        Image rollover = getImage(64, Color.ORANGE).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
        setRolloverIcon(new ImageIcon(rollover));
        setBorderPainted(false);
        setContentAreaFilled(false); 
    }
}

class ButtonHandler implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        MyButton mb = (MyButton) e.getSource();
        mb.setYellow();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM