저는이 문제에 대한 해결책을 찾고 있습니다.이 문제와 관련된 비슷한 게시물을 읽었지만 어느 것도 저에게 효과적이었습니다.JButton 이미지 아이콘이 .png 파일로 표시되지 않습니다.
"b.png"을 JButton에 표시하려고하는데 버튼을 롤오버하면 아이콘이 바뀝니다.
package GUI_JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Gui extends JFrame {
private JButton reg;
private JButton custom;
public Gui() {
super("Title goes here");
setLayout(new FlowLayout());
reg = new JButton("reg button"); // create reg button
add(reg); // add reg button to JFrame
// initialize images
Icon b = new ImageIcon(getClass().getResource("images/imageA.png"));
Icon x = new ImageIcon(getClass().getResource("images/imageB.png"));
custom = new JButton("custom button", b); // create custom button
custom.setRolloverIcon(x);
add(custom); // add button to JFrame
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null,
String.format("%s", event.getActionCommand()));
}
}
}
이미지는 Gui.java
파일과 TESTMain.java
파일과 함께 src 폴더에있는 폴더라는 이름의 이미지에 있습니다.
내가 얻는 오류는 Main에서 null 포인터 예외입니다. 시도했습니다
Icon b = new ImageIcon("images/imageA.png");
이 컴파일되지만 이미지는 표시되지 않습니다. 또한
custom = new JButton("custom", new ImageIcon("images/imageA.png"));
그리고
custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png"));
나는 이미지가 항아리로 컴파일해야하기 getClass().getResource()
이 prefferred 것을 알고 시도했다.
이미지를 표시하기위한 아이디어가 있습니까?
'getResource ("images/imageA.png")'를'getResource ("/ images/imageA.png")'로 변경하십시오. –