Java语言程序设计课程实验题目
第六次实验
1. 在IDE中输入并观察以下代码,分析该段程序的作用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJProgressBar extends JFrame implements ActionListener{
Container ctp = getContentPane();
JPanel jp = new JPanel();
JProgressBar tp = new JProgressBar(JProgressBar.HORIZONTAL, 0, 300);
public static void main(String[] args) {
TestJProgressBar tj = new TestJProgressBar();
tj.launchFrame();
}
public void launchFrame() {
JButton jb1 = new JButton("Start");
jb1.addActionListener(this);
ctp.add(tp, BorderLayout.NORTH);
ctp.add(jp, BorderLayout.CENTER);
jp.add(jb1);
jp.setLayout(new FlowLayout());
this.setSize(200,100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
tp.setValue(0); // clear
MyRunner mr1 = new MyRunner();
Thread th1 = new Thread(mr1);
th1.start();
return;
}
class MyRunner implements Runnable {
public void run() {
while(tp.getValue() < tp.getMaximum()) {
tp.setValue(tp.getValue() + 1);
try {
Thread.sleep(20);
}catch(InterruptedException e) {}
}
}
}
}
2. 在IDE中输入并观察以下代码,分析该段程序的作用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJRadioButton implements ActionListener {
JLabel jl = new JLabel("Please select your gender");
ButtonGroup bg = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Male", false);
JRadioButton rb2 = new JRadioButton("Female", false);
public void launchFrame() {
JFrame f = new JFrame("Test JRadioButton");
Container ct = f.getContentPane();
ct.setLayout(new FlowLayout());
ct.add(jl); ct.add(rb1); ct.add(rb2);
// add two radio buttons into same button group
bg.add(rb1); bg.add(rb2);
// add Listener for two radio buttons
rb1.addActionListener(this); rb2.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200,100); f.setVisible(true);
}
public static void main(String[] args){
TestJRadioButton tr = new TestJRadioButton();
tr.launchFrame();
}
public void actionPerformed(ActionEvent e ) {
String rbt = e.getActionCommand();
System.out.println("You selec