java - 如何在图像上放置 JButton?

标签 java swing size jbutton paintcomponent

我正在尝试修复一个 JFrame,其中将有一个背景图像和图像上的 JButtons,它将执行一些命令。我尝试在没有布局的情况下进行操作,因为我想在 JFrame 的某些特定位置放置小按钮,但每次我这样做时,背景图像都会出现在前面,或者 JFrame 的大小等于 JFrame 的大小。使用以下代码,JButton 与 JFrame 具有相同的大小。我试图改变 JButton 的大小和位置,但没有改变。你能帮帮我吗?

这是代码


public final class Test extends JComponent
{
 private Image background;
 private JFrame frame;
 private Dimension dimension;<p></p>

<pre><code>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
</code></pre>

<p>//        label();</p>

    test = displayButton("test");
}

public JButton displayButton(String name)
{
    JButton button = new JButton(name);

    button.setSize(100, 100);
    button.setPreferredSize(dimension);
    return button;
}

最佳答案

您需要更改 content pane 以获得您的 Frame 的背景。

public static void main(String[] args) throws IOException {

    JFrame frame = new JFrame("Test");

    frame.setContentPane(new JPanel() {
        BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, 300, 300, this);
        }
    });

    frame.add(new JButton("Test Button"));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

输出:

screenshot

关于java - 如何在图像上放置 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5912913/

相关文章:

java - JNA 传递包含指向结构的指针和指向原语的指针的结构

Java全屏独占模式

mongodb - 删除大量数据后如何减少MongoDB存储空间

interface - 使用接口(interface)宽度和 $size 自动 SystemVerilog 可变大小?

java - 如何测量 jit 编译开销

java - 在 Eclipse 中增强 openJPA 类

java - 如何在 Swing 组件中显示 Flash 动画?

java - 基本 GUI : Computing for the area and perimeter of a rectangle, 代码有效,但 "variables are never read"

c# - Visual C# 2010 速成版 : Same Form But Different Size on Win7 and WinXP

java - 在 SimpleDateFormat#parse() 中使用 ~