jbutton id没有显示

时间:2013-03-21 06:40:46

标签: java swing jbutton

我刚创建了一个简单的图像面板,并在面板上添加了一个按钮

任何人都能告诉我代码中的问题吗?

图像正在显示,但按钮不是

package inventorymanagement;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageTest {

public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("E:/Desktop[/icon/6470729-exclamation-mark-icon-button-3d-red-glossy-circle.jpg").getImage());
JButton jButton1=new JButton("jButton1");
panel.add(jButton1);

JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

}
}

class ImagePanel extends JPanel {

private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}

public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}



public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}

}

2 个答案:

答案 0 :(得分:0)

您必须设置面板的布局

在添加按钮panel.setLayout(new java.awt.FlowLayout());之前添加panel.add(jButton1);

答案 1 :(得分:0)

当你setLayout(null);时,你需要将setBounds设置为所有组件。您应该阅读以下教程:http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html