我正在尝试修复一个JFrame,其中将有一个背景图像和图像JButtons将执行一些命令 . 我尝试在没有布局的情况下这样做,因为我想在JFrame上的某些特定位置放置小按钮,但每次我这样做时,背景图像都会出现在前面,或者JFrame的大小等于JFrame大小 . 使用以下代码,JButton与JFrame具有相同的大小 . 我试图改变JButton的大小和位置,但没有 . 你能帮我吗?
这是代码
public final class Test extends JComponent
{
private Image background;
private JFrame frame;
private Dimension dimension;
public Test()
{
dimension = new Dimension(15, 15);
frame = new JFrame("Iphone");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this);
frame.setBounds(641, 0, 344, 655);
frame.setVisible(true);
test = displayButton("tigka");
frame.getContentPane().add(test);
}
public void update(Graphics g)
{
paint(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(background, 0, 25, null); // draw background
// label();
test = displayButton("test");
}
public JButton displayButton(String name)
{
JButton button = new JButton(name);
button.setSize(100, 100);
button.setPreferredSize(dimension);
return button;
}
4 回答
您需要更改
content pane
以获取Frame
的背景 .输出:
您是否尝试在标签中使用带有HTML的JLabel?像这样的东西:
然后在你的标签上你可以添加你的按钮?
你应该交换这两行:
因此它应该是这个顺序:
此外,请注意内容窗格的默认布局是BorderLayout . 因此,您可以将内容窗格的布局显式设置为null .