如何将图像放到Jbutton上

时间:2016-11-09 20:12:36

标签: java swing

我在如何在java上编写这个简单的老虎机时遇到了很多麻烦,第一个应该最容易解决的问题是当我在eclipse上运行程序时将3个.png图像放到JButton上。所有文件也在源文件夹中。

以下是我的代码现在的样子:

public static void main(String[] args) throws IOException {

    Stack stack = new Stack();
    Queues queue = new Queues();

    File stackfile = new File("stack.txt");

    if (!stackfile.exists()) {
        stackfile.createNewFile();
    } else {
        System.out.println("File is done");
    }
    FileReader r = new FileReader(stackfile);
    BufferedReader reader = new BufferedReader(r);

    String line = null;

    // Skip headline
    reader.readLine();

    while ((line = reader.readLine()) != null) {

        String[] splitLine = line.trim().split("#");

        if (splitLine.length == 3)
            stack.Push(new Data(splitLine[1], splitLine[2], splitLine[0]));
    }

    reader.close();

    File queuefile = new File("queue.txt");

    if (!queuefile.exists()) {
        queuefile.createNewFile();
    } else {
        System.out.println("File is done");
    }

    BufferedReader read = null;
    read = new BufferedReader(new FileReader(queuefile));

    // Skip headline
    read.readLine();

    while ((line = read.readLine()) != null) {

        String[] splitLine = line.trim().split("#");

        if (splitLine.length == 3)
            queue.insert(new Data(splitLine[1], splitLine[2], splitLine[0]));
    }

    read.close();

}

1 个答案:

答案 0 :(得分:2)

你正在为JButton使用错误的构造函数。那个只设置标题。

使用允许您设置文本和图标的构造函数。

ImageIcon icon = createImageIcon("images/middle.gif",
                                 "a pretty but meaningless splat");
label1 = new JButton("Image and Text", icon);

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}