我试图在我的GUI中添加一个图像按钮,但我得到的只是一个空白屏幕。任何人都可以告诉我我的代码有什么问题吗?这是我到目前为止所做的。
package fallingStars;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame
{
private JLabel label;
private JButton button;
private JPanel buttonPanel;
public static void startButton()
{
ImageIcon start = new ImageIcon("Start.png");
JButton play = new JButton(start);
play.setBounds(150,100,100,50);
}
public static void main(String args[])
{
GUI gui = new GUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 500);
gui.setVisible(true);
gui.setResizable(false);
gui.setTitle("Falling Stars");
JPanel panel = new JPanel();
startButton();
}
}
答案 0 :(得分:2)
您必须使用container.add(JButton);
将JButton添加到容器中如果您实际上没有添加它,您将会出现空白屏幕:)
答案 1 :(得分:1)
首先只需在 JLabel 中插入 ImageIcon 即可。如果您希望图像充当按钮,则必须添加 MouseListener &像我一样实施 mouseClicked()。
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class MyFrame extends JFrame{
private JLabel label;
private static MyFrame frame;
public MyFrame(){
initComponent();
label.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
JOptionPane.showMessageDialog(frame, "You just clicked the image");
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
private void initComponent() {
this.setSize(400, 400);
this.setLocationRelativeTo(null);
label = new JLabel();
label.setIcon(new ImageIcon(getClass().getResource("res/image.png")));
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible (true);
}
public static void main(String[] args) {
frame = new MyFrame();
}
}