0

重複の可能性:
Netbeans で画像パスを使用して JPanels に画像を表示する方法

ボタンと JPanels を備えた GUI を用意しました。JFrame でボタンをクリックすると、3 つのことが起こる必要があります。2 つの大きなイメージ (ソース パッケージからのパスで指定) が 2 つの個別の JPanel に表示され、空の JLabel に短いテキスト文字列 (これから記述します) が表示される必要があります。問題は、ボタン処理コードの書き方がわからないことです。また、機能させるためにいくつかの初期化コンポーネントを実装する必要があるかどうかもわかりません。サンプルコードは次のとおりです。

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?...
         */
    }
4

1 に答える 1

2

これが私のプロジェクトなら、

  • プログラムの起動時に画像をアップロードし(画像が多すぎず、大きすぎない場合)、ImageIconsに配置します。
  • GUI ですでに表示されている JLabels の ImageIcons を表示する
  • JButton の ActionListener コードで、setIcon(...)メソッドを介してイメージ JLabel の ImageIcon を設定し、 を介してテキスト JLabel のテキストを設定しsetText(...)ます。
  • 実際、画像とテキストを互いに近づけて適切な向きにする場合は、1 つの JLabel を使用して画像とテキストの両方を保持できます。
  • また、NetBeans の Matisse ドラッグ アンド ドロップ GUI クリエーターなど、コード ジェネレーターを使用して Swing コードを生成しているようです。あなたは Swing に慣れていないので、これは脇に置いて、最初は手で Swing をコーディングする方法を学び、あとで Swing に十分慣れてから、必要なコード ジェネレーターを使用することを強くお勧めします。これにより、早い段階で悲しみの世界を救うことができます。

より具体的なアドバイスが必要な場合は、以前に提案したように、これをコーディングしようとした実際の試み (生成されたコードのスケルトンではありません。コードを確認する必要があります) と、現在発生している問題の詳細な説明を提示してください。コードの試みは持っています。

于 2012-10-19T18:01:50.250 に答える