4

メッセージダイアログボックスに画像を追加する方法を知りたいです。以下のコードを試してみましたが、画像がどこにも見つかりませんでした

else if(button == B){
String text = "blahblahblahblahblah";
    JTextArea textArea = new JTextArea(text);

textArea.setColumns(30);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
JOptionPane.showMessageDialog(
null, textArea, "Border States", JOptionPane.PLAIN_MESSAGE);

image2 = new ImageIcon(getClass().getResource("borderstates.jpg"));
  label2 = new JLabel(image2);
  add(label2);
4

3 に答える 3

20

JOptionPane非常に柔軟な API です。

最初の呼び出し先はJava API DocsJava Trails、特定のHow to use Dialogsである必要があります

ここに画像の説明を入力ここに画像の説明を入力

public class TestOptionPane04 {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ImageIcon icon = new ImageIcon(TestOptionPane04.class.getResource("/earth.png"));
                JOptionPane.showMessageDialog(
                        null,
                        "Hello world",
                        "Hello", JOptionPane.INFORMATION_MESSAGE,
                        icon);
                JOptionPane.showMessageDialog(
                        null,
                        new JLabel("Hello world", icon, JLabel.LEFT),
                        "Hello", JOptionPane.INFORMATION_MESSAGE);

            }
        });
    }
}
于 2012-12-20T00:47:06.860 に答える
5

JOptionPaneのjavadocから:

public static void showMessageDialog(Component parentComponent,
                                     Object message,
                                     String title,
                                     int messageType,
                                     Icon icon)
                          throws HeadlessException

Icon画像を作成して、5番目のパラメータとして追加するだけです。

JOptionPane.showMessageDialog(null, textArea, "Border States", 
    JOptionPane.PLAIN_MESSAGE, image2);

使用する前にimage2を定義することを忘れないでください(ラインを上に移動してください)

于 2012-12-20T00:27:51.690 に答える
5

MessageDialogBox とは何ですか? JOptionPane に画像を追加する場合は、Icon を受け入れるメソッド オーバーロードが存在するため、これがこれを解決する 1 つの方法です。もう 1 つは、イメージとその他のコンポーネントを使用して JPanel または JLabel を作成し、これを JOptionPane に表示する方法です。

于 2012-12-20T00:19:24.887 に答える