具有图像背景和文本对齐方式的JButton [英] JButton with image background and text alignment

查看:37
本文介绍了具有图像背景和文本对齐方式的JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我再次遇到一个问题:我在背景上有一个jbutton,上面有一个图像,但是当我想在上面放一些文字时,它会在背景的右侧出现,而不是在按钮的右边,而是放在一边... 这是工作代码,您只需链接一些图像即可:)

I've got (again) a problem: i got a jbutton with an image on background, but when i want to put some text on it, it will apears on the right side of background, not in button, but aside... Here is working code, you must only link some image :)

package program;

import java.awt.Image;
import java.awt.Insets;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Program {
    private static JFrame frame;
    private static JPanel panel;
    private static JButton button;
    private static Image buttonImage;
    private static ImageIcon buttonIcon;

    public static void main(String[] args) {
        frame = new JFrame("Program");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setSize(200,100);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        String imgUrl = "images/";
        try {
            buttonImage = ImageIO.read(new File(imgUrl+"img.png"));    
        } catch (IOException e) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, e);
        }
        buttonIcon = new ImageIcon(buttonImage);
        button = new JButton("TEST", buttonIcon);
        panel.add(button);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setBounds(0, 0, 146, 67);
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
    }
}

推荐答案

您从不设置背景,而是设置按钮的图标

you never set the background,you'v set the icon of the button

这篇关于具有图像背景和文本对齐方式的JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆