通过按钮同时显示图像和文本字符串[复制]

问题描述 投票:0回答:1

可能重复: How to display images on JPanels using image paths in Netbeans

我已经准备了一个带按钮和Jpanel的GUI。在JFrame中单击按钮时,需要执行3项操作。两个大图像(由源包中的路径指定)必须出现在两个单独的JPanel上,并在一个空的JLabel中出现一小段文本(我将编写)。问题是我无法弄清楚应该如何编写按钮处理代码。我也不知道是否需要实现一些init组件才能使它工作。这是一些示例代码:

package db.SuperMarioGFX;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/**
 *
 * @author speterson86
 */
public class EnemyGFX extends javax.swing.JFrame {

    /**
     * Creates new form EnemyGFX
     */
    public EnemyGFX() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     *
     * SuppressWarnings("unchecked"), followed by over 1000 lines of Generated
     * Code are below this, but not necessary to include in this code sample!
     */
    private void btnBeachKoopaActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        /**
         * For 'Land[JPanel]' (Panel-container for a set of buttons, not for
         * displaying images)
         *
         * Note that "pbx" is short for "picture box". Unlike VB, I couldn't
         * find any so-called picture boxes when I was building my GUI in
         * Netbeans, so I hoped JPanels would be the next best thing to use for
         * displaying relatively large (roughly 400 x 400 pixels or less each)
         * images. Now, here's the 3 things I need to display on my EnemyGFX
         * JFrame when the btnBeachKoopa button is clicked on:
         *
         * Display "GFX01.png" in pbxDefaultBinFile[JPanel] 
         * Display "Yoshi'sIsland2.zst, Level #$106" text in lblSaveState[JLabel] 
         * Display "Land1.PNG" in pbxFixedBinFile[JPanel]
         *
         * So how would I go about making that happen?...
         */
    }
java image swing jpanel jlabel
1个回答
2
投票

如果这是我的项目,我会考虑

  • 在程序启动时上传图像(如果没有太多图像,如果不是太大)并放入ImageIcons。
  • 在JLabels中显示已由GUI显示的ImageIcons
  • 在JButton的ActionListener代码中,通过setIcon(...)方法设置图像JLabel的ImageIcon,通过setText(...)设置文本JLabel的文本。
  • 实际上,如果图像和文本彼此靠近并且方向适当,则可以使用一个JLabel来保存图像和文本。
  • 此外,您似乎正在使用代码生成器生成Swing代码,例如NetBeans的Matisse拖放GUI创建器。由于你是Swing的新手,我强烈建议你把它放在一边,先学会手工编写Swing,然后才能熟悉Swing使用你想要的代码生成器。这将在早期为您节省一个悲伤的世界。

如果您需要更具体的建议,那么正如我们之前建议的那样,请向我们展示您对此进行编码的实际尝试(不是生成代码的框架 - 我们需要查看您的代码)以及您当前遇到的问题的详细说明代码尝试正在进行。

© www.soinside.com 2019 - 2024. All rights reserved.