如何在Swing输入对话框文本框中获取用户输入

说明

以下示例展示了如何在Swing输入对话框文本框中获取用户输入。

我们正在使用以下 API。

  • JOptionPane : 创建一个标准对话框。

  • JOptionPane.showInputDialog() : 显示带有输入选项的消息警报。

  • options as null : 在输入框中显示文本框。

代码示例

package com.yiidian;

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

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("一点教程网:Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            String result = (String)JOptionPane.showInputDialog(
               frame,
               "Select one of the color", 
               "Swing Tester",            
               JOptionPane.PLAIN_MESSAGE,
               null,            
               null, 
               "Red"
            );
            if(result != null && result.length() > 0){
               label.setText("You selected:" + result);
            }else {
               label.setText("None selected");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);
   }  
} 

执行效果如下:

热门文章

优秀文章