如何使用输入添加java图标和阵容文本?

时间:2013-10-25 14:34:31

标签: java swing

根据这张照片,我正试图得到相同的结果:

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);
}

1 个答案:

答案 0 :(得分: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);
               }

            }
        });
    }
}

教程资源: How to make Dialogue