将图像添加到JButton

时间:2014-08-19 16:24:42

标签: java swing jframe jbutton imageicon

我想将图像添加到我的JButtons中。我试图将rollover icon命令添加到我的一个按钮,但即使eclipse没有说有任何错误,我仍然会收到异常。我已将图像保存在工作区/ projectname / src中,类文件在这里,它们被称为a和b,它们是JPEG图像。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

    public class button extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton hi;
    private JButton custom;

    public button() {
        super("The title");
        setLayout(new FlowLayout());

        hi = new JButton("Hi button");

        Icon a = new ImageIcon(getClass().getResource("a.JPEG"));
        Icon b = new ImageIcon(getClass().getResource("b.JPEG"));
        custom = new JButton("custom", a);
        custom.setRolloverIcon(b);
        add(custom);
        add(hi);

        HandlerClass handler = new HandlerClass();
        hi.addActionListener(handler);
        custom.addActionListener(handler);

    }
    private class HandlerClass implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
        }
    }
}

import javax.swing.JFrame;
public class buttonm {
    public static void main(String[] args) {
        button hello = new button();
        hello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        hello.setSize(350,100);
        hello.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:0)

Button类

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Button extends JFrame {

    private JButton button;
    private JPanel p;

    public Button() {
        super("The title");
        p = new JPanel(new BorderLayout());
        button = new JButton();

        ImageIcon icon = new ImageIcon(getClass().getResource("button2.jpg"));
        button.setIcon(icon);
        button.setDisabledIcon(icon);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 400);
        p.add(button);
        add(p);

    }
}

你的主要班级

public static void main(String[] args) {
        Button btn = new Button();
        btn.setVisible(true);
    }