如何将图像添加到JButton?

时间:2017-09-06 13:02:05

标签: java jbutton

请帮忙。我到处搜索但我无法将图像添加到JButton。

我尝试过setIcon(),但这并没有奏效。 我制作游戏,我的图像路径是/textures/StartButton.png

有我的代码:

package com.GermanySimulator.states;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import com.GermanySimulator.display.Window;
import com.GermanySimulator.graphics.AssetsLoader;

public class MainMenuState extends State {

@SuppressWarnings("unused")
private MouseEvent e;
private int StartButtonWidth = 100;
private int StartButtonHeight = 50;
private int StartButtonX = Window.width / 2 - StartButtonWidth;
private int StartButtonY = Window.height / 4;
@SuppressWarnings("unused")
private State gamestate = new GameState();
static Icon StartIcon = new ImageIcon("/textures/StartButton.png");
public static JButton StartButton = new JButton(StartIcon);
public static boolean clicktimer = true;

@Override
public void tick() {
}

@Override
public void render(Graphics g) {
    g.drawImage(AssetsLoader.mainmenu, 0, 0, null);
    StartButton.setBounds(StartButtonX, StartButtonY, StartButtonWidth, StartButtonHeight);
    StartButton.setVisible(true);
    StartButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(clicktimer == true) {
            System.out.println("Click!");
            clicktimer = false;
            }
        }   
    });
}
}

2 个答案:

答案 0 :(得分:0)

使用javax.imageio.ImageIO,它应该工作,确保路径正确,如果您不确定只是提供所有路径(c:\ folder \ .... \ textures \ StartButton.png)并尝试类似的东西。

JButton StartButton = new JButton();
      try {
        Image startImage =ImageIO.read(getClass().getResource("/textures/StartButton.png"));
        StartButton.setIcon(new ImageIcon(startImage));
      } catch (Exception ex) {
        System.out.println(ex);
      }

答案 1 :(得分:0)

使用java.awt.Toolkit

Image image = java.awt.Toolkit.getDefaultToolkit().getImage("/textures/StartButton.png");
JButton button = new JButton(new ImageIcon(image));

注意,getImage()缓存图像。如果您想避免这种情况,请改用createImage()