设计图:
类MyFrame:
设计思路:
1、设置底层面板并添加“测试”按钮
2、对按钮添加监听器
3、设计监听器里面的方法
3.1、添加对话框并设置其面板内容
3.2、添加lamada型简化监听器(当点击确定按钮时,对话框消失,最后返回用户的textfield的输入)
package swing01;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyFrame extends JFrame{
public MyFrame(String title)
{
super(title);
JPanel root=new JPanel();
this.setContentPane(root);
root.setLayout(new FlowLayout());
//向根面板添加一个按钮
JButton testButton=new JButton("测试");
root.add(testButton);
//监听器
testButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str=getUserInput();
System.out.println("用户输入了:"+str);
}
});
}
public String getUserInput()
{
//创建JDialog
JDialog dialog=new JDialog(this,"信息框",true);
JPanel panel=new JPanel();
panel.setLayout(new FlowLayout());
dialog.setContentPane(panel);
//添加控件到对话框
JTextField testfield=new JTextField(20);
JButton button=new JButton("确定");
panel.add(testfield);
panel.add(button);
//点击按钮时,关闭对话框
button.addActionListener((e)->{
dialog.setVisible(false);
});
//显示对话框(setVisible()方法会阻塞,直到对话框关闭)
dialog.setSize(300, 100);
dialog.setVisible(true);
//对话框被关闭后,取得用户输入,并返回
String text=testfield.getText();
return text;
}
}
类MyDemo:
package swing01;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyDemo
{
private static void createGUI()
{
// JFrame指一个窗口,构造方法的参数为窗口标题
JFrame frame = new MyFrame("测试");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口的其他参数,如窗口大小
frame.setSize(400, 300);
// 显示窗口
frame.setVisible(true);
}
public static void main(String[] args)
{
//设置界面样式 Look And Feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createGUI();
}
});
}
}