2

所以我试图得到同样的结果,根据这张照片:

halp.png

我试图让底部 2 看起来像上面 2。
所以第一个问题是我没有得到标题中的 java 图标。
第二个问题是“一些文本:”没有与输入框对齐。

这是我的代码:

    public static void main(String[] args) {

    String input = JOptionPane.showInputDialog(null, "Some Text:", "Dialog",
            JOptionPane.PLAIN_MESSAGE);
    if(input != null)
        JOptionPane.showMessageDialog(null, "Value entered: " + input, "Message box", JOptionPane.INFORMATION_MESSAGE);
    else
        System.exit(0);
}
4

1 回答 1

3

我们可以将 Swing 组件添加到JOptionPane. 那么为什么不创建一个包含JLabelJTextFeild布局的自定义面板,即,FlowLayout并将该面板添加到 JOptionPane 使用

   JOptionPane.showConfirmDialog
   (
        frame, // main window frame
        customPanel, // custom panel containing the label and textFeild
        "My Panel with Text Feild", // Title
        JOptionPane.OK_CANCEL_OPTION, // with OK and CANCEL button
        JOptionPane.PLAIN_MESSAGE 

   ); 

一个最小的工作示例:

import java.awt.event.*;
import javax.swing.*;

class CustomPanel extends JPanel
{
    JLabel lab;
    JTextField txtField;

    public CustomPanel() {

        lab = new JLabel("Some Text: ");
        txtField = new JTextField(20);

        add(lab);
        add(txtField);

    }

    public String getText()
    {
       return txtField.getText();
    }

}

public class JOptionPaneDemo {


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CustomPanel inputPane = new CustomPanel();
               int value = JOptionPane.showConfirmDialog(null, inputPane, "Demo" ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
               if(value == JOptionPane.OK_OPTION)
               {
                   JOptionPane.showMessageDialog(null, "Value Entered: "+inputPane.getText(), "Demo", JOptionPane.INFORMATION_MESSAGE);
               }

            }
        });
    }
}

教程资源: 如何进行对话

于 2013-10-25T14:45:11.587 回答