java Swing做一个简单的文本输入框,
新建一个SwingDemo类:
////java swing做一个简单的文本框//Created by lee_1310 on .03.29 23:05//CopyRight @ /Lee_1310.//import javax.swing.JFrame;public class SwingDemo {public static void main(String[] args){javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run(){createGUI();}});}private static void createGUI(){//创建一个窗口,创建一个窗口myFrame frame = new myFrame("SwingDemo!");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗口大小frame.setSize(600, 400);//显示窗口frame.setVisible(true);}}
再创建一个继承与JFrame的myFrame
//myFrame基于JFrame的个人工具类import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.AbstractButton;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;public class myFrame extends JFrame{JLabel label = new JLabel("姓名"); //创建JTextField,16表示16列,用于JTextField的宽度显示而不是限制字符个数JTextField textField = new JTextField(16);JButton button = new JButton("确定");//构造函数public myFrame(String title){//继承父类,super(title);//内容面板Container contentPane = getContentPane();contentPane.setLayout(new FlowLayout());//添加控件contentPane.add(label);contentPane.add(textField);contentPane.add(button);//按钮点击处理 lambda表达式button.addActionListener((e) -> {onButtonOk();});}//事件处理private void onButtonOk(){String str = textField.getText();//获取输入内容//判断是否输入了if(str.equals("")){Object[] options = { "OK ", "CANCEL " }; JOptionPane.showOptionDialog(null, "您还没有输入 ", "提示", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);}elseJOptionPane.showMessageDialog(this,"您输入了:" + str);}}
运行结果如下:
当没有输入点击确定按钮
正确输入后: