【问题标题】:Why don't I see the image or the button?为什么我看不到图像或按钮?
【发布时间】:2013-09-04 07:32:06
【问题描述】:

我正在尝试在图像上添加一个按钮。但既看不到按钮也看不到图像。这是为什么 ?我在 IDE 调用 initComponents 方法之后从构造函数调用此方法。

public void initD() {
    try {
        BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        JButton b = new JButton("Press me");
        jPanel1.add(picLabel);
        jPanel1.add(b);
        System.out.println("last statement");
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

我只将帧视为输出。

【问题讨论】:

  • 您使用的是什么布局管理器?你知道JButton 支持图标吗?
  • 如需尽快获得更好的帮助,请发帖SSCCE
  • @MadProgrammer IDE 使用的默认值。我刚刚添加了这个方法。我必须在图像上添加许多按钮。
  • 如果 IDE 的默认值是 GroupLayout,那么动态添加它是很棘手的。使用带有不同布局管理器的帮助面板(情况有点类似here)。
  • GroupLayout 需要将组件添加到 layout,而且方式相当复杂。将jPanel1 的布局管理器更改为更合适的内容(如果jPanel1 有一些其他已使用IDE 放置的内容,则使用帮助面板)。

标签: java image swing netbeans jbutton


【解决方案1】:

我不知道您使用的是哪种布局,但是您应该像这样实现button.setIcon();

public void initD() {
    JButton button = new JButton("Press me");
    try {
        BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));

        button.setIcon(new ImageIcon(myPicture));

        System.out.println("last statement");
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

此外,您可能需要考虑图像资源,也许这种实施可能会有所帮助;

ImageIO.read(getClass().getResource("resources/meaning.JPG")));

【讨论】:

  • 我想要图像上的按钮..而不是按钮上的图像
  • @saplingPro :请看一下这个答案,关于adding background image,希望它可以帮助你。尽管 cmets 中指向您问题的最后一个链接是一种更好的方法,可以在 JPanel 上绘制图像并向其添加组件,而不是将组件放在 JLabel 上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2020-05-22
  • 1970-01-01
  • 2011-06-25
  • 2020-12-07
  • 2023-04-08
相关资源
最近更新 更多