Java基础知识(3): Swing编程

1、主要内容

通过Swing编写图形用户界面

2、Swing控件编程

用Swing编写图形用户界面主要涉及JFrame, JPanel, JButton等等类。其中,JFrame是界面布局的桌子;JPanel是放置控件的幕布,铺在JFrame上将空间分成若干块;JButton等控件添加到JPanel的指定位置中。

2.1JFrame相关方法

setTitle("")设置窗口名称

setBounds()设置窗口位置和尺寸

setLayout(null)关闭窗口布局管理器使得后面的setBounds生效

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)定义窗口关闭事件

setResizable(false)禁用最大化

getContentPane()返回窗体的contentPane对象

getContentPane().add(JPanel)添加JPanel容器

2.2 JPanel相关方法

setBounds()设置窗口位置和尺寸,在JFrame内的相对位置

setLayout(null)关闭窗口布局管理器使得控件的setBounds生效

add()添加控件

2.3 JButton等控件

setBounds()设置窗口位置和尺寸,在JPanel内的相对位置

代码如下:

public class mainFrame extends JFrame{

	public TextArea revArea;
	public JButton button1;
	public JButton button2;
	public JButton button3;
	public JButton button4;
	public JButton button5;
	public JButton button6;
	
	
	public mainFrame() {
		
		this.setTitle("服务器");
		this.setBounds(300, 200, 500, 500);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(null);
		this.setResizable(false);
		
		JPanel panel_1 = new JPanel();
		panel_1.setLocation(350, 20);
		panel_1.setSize(100, 300);
		panel_1.setLayout(null);
		
		button1 = new JButton("Exp 1");
		button1.setBounds(0, 0, 100, 30);
		button2 = new JButton("Exp 2");
		button2.setBounds(0, 50, 100, 30);
		button3 = new JButton("Exp 3");
		button3.setBounds(0, 100, 100, 30);
		button4 = new JButton("Exp 4");
		button4.setBounds(0, 150, 100, 30);
		button5 = new JButton("保存");
		button5.setBounds(0, 200, 100, 30);
		button6 = new JButton("任务取消");
		button6.setBounds(0, 250, 100, 30);
		
		panel_1.add(button1);
		panel_1.add(button2);
		panel_1.add(button3);
		panel_1.add(button4);
		panel_1.add(button5);
		panel_1.add(button6);
		
		
		this.getContentPane().add(panel_1);
		
		revArea = new TextArea();
		revArea.setBounds(10, 10, 280, 440);
		
		this.getContentPane().add(revArea);
		
		Event();
		
	}

3、Swing的并发

当一个Swing控件触发一个长期运行任务时,那么这个长期运行任务就占用了事件分发线程(图形界面的线程),导致按钮无法立刻弹起来。解决方法是在响应触发时分配单独的线程执行长期运行的任务。可以使用单线程的Executor线程池,它自动将待处理任务排队,然后按顺序执行。

button2.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				revArea.append("实验二
");
				executor.execute(new Runnable() {
					public void run() {
						c.Experment_2(file);
					}
				});
			}
			
		});

其中,c.Experment_2()是一个长期运行任务。

public ExecutorService executor = Executors.newSingleThreadExecutor();

4、遗留的问题

在实际问题中遇到了如何异步终止线程的问题。

一般的方法是通过外部方法改变control变量的值来终止线程

while (control) {
			
			}

但是在有阻塞IO或等待锁时,无法用这种方法来终止。

经验分享 程序员 微信小程序 职场和发展