JFrame、模态JDialog、ActionListener、setResizable()综合练习 (详细解析)

问题:

设计一个JFrame,上面有一个按钮,文字是 "打开一个模态窗口"。
点击该按钮后,随即打开一个模态窗口。
在这个模态窗口中有一个按钮,文本是 "锁定大小", 点击后,这个模态窗口的大小就被锁定住,不能改变。 再次点击,就回复能够改变大小。

解决:

package 容器和布局器;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class 模态与大小变化练习 {
public static void main(String[] args) {
	JFrame f=new JFrame("林科大");
	f.setSize(400,400);
	f.setLocation(100,100);
	f.setLayout(null); //设置窗口中的组件位置为绝对定位
    
	JButton b1=new JButton("打开模态对话框");
	b1.setBounds(100,50,200,50);//设置按钮位置及大小
	
	JDialog d=new JDialog(f);//根据外部窗口实例化JDialog
	d.setModal(true);//设置JDialog为模态
	
		 d.setTitle("计信学院");
		 d.setSize(200,200);
		 d.setLocation(200,250);
		 d.setLayout(null);
		 
	JButton b2=new JButton("锁定大小");
	b2.setBounds(50,50,100,50);
	
	//对按钮b1进行监听
	b1.addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
		 d.setVisible(true);
		 
		 
			
		}
	});
	
	//对按钮b2进行监听
	b2.addActionListener(new ActionListener() {
			 public void actionPerformed(ActionEvent e) {
				
					 if(d.isResizable()==true) {
						 d.setResizable(false);
						 b2.setText("解锁大小");
					 }
					 else {
						 d.setResizable(true);
						 b2.setText("锁定大小");
					 
				 }
			 }
		 });
	
	f.add(b1);
	d.add(b2);
	f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时退出程序
	f.setVisible(true);//设置窗口为可见
	
}
}

猜你喜欢

转载自blog.csdn.net/qq_44624536/article/details/114270588