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 selected " + rbt);
}
}
3. 在IDE中输入并观察以下代码,分析该段程序的作用。
import java.io.*;
public class WriteFile {
public static void main (String[] args) {
File file = new File("newfile.txt");
try {
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
// Create a print writer on this file.
PrintWriter out = new PrintWriter(new FileWriter(file));
String s;
System.out.print("Enter file text. ");
System.out.println("[Type ctrl-d (or ctrl-z) to stop.]");
// Read each input line and echo it to the screen.
while ((s = in.readLine()) != null) { out.println(s); }
// Close the buffered reader and the file print writer.
in.close();
out.close();
} catch (IOException e) {
// Catch any IO exceptions.
e.printStackTrace();
}
}
}
4. 编写程序。
构建如图所示界面,
当用户勾选响应的物品时,请按照响应的数字相加求和。
注意,改程序应允许用户反复使用,无需每轮计算都要运行启动程序。
5. 编写程序。
采用可视化用户界面,构建程序。要求允许采用(1)文件导入(请自行查询Java的文件处理方法,配合使用JFileChooser)或(2)手工输入等两种方式向程序输入文本内容,对文本内容进行分析,识别得出文字中包含的字符成分,包括:大写字母、小写字母、空格、数字、其他符号,并归类之后在界面上输出结果。
1、
package org.cust.test6;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJProgressBar extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
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(1200, 1200);
this.setVisible(true);
this.setResizable(true);
this.setLocationRelativeTo(null);
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) {
}
}//进度条最大值300,每20毫秒+1的进度的速度跑满
}
}
}
2、
package org.cust.test6;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
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(800, 800);
f.setLocationRelativeTo(null);
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 selected " + rbt);
}
//此段代码是界面性别选择的单选框
//通过ButtonGroup嵌套JRadioButton实现单选
}
3、
package org.cust.test6;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class WriteFile {
public static void main(String[] args) {
File file = new File("newfile.txt");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a print writer on this file.
PrintWriter out = new PrintWriter(new FileWriter(file));
String s;
System.out.print("Enter file text. ");
System.out.println("[Type ctrl-d (or ctrl-z) to stop.]");
// Read each input line and echo it to the screen.
while ((s = in.readLine()) != null) {
out.println(s);
}
// Close the buffered reader and the file print writer.
in.close();
out.close();
} catch (IOException e) {
// Catch any IO exceptions.
e.printStackTrace();
}
}
// 此段代码为文本输入,键盘点击 ctrl-d (or ctrl-z) 终止输入
}
4、
package org.cust.test6;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestJCheckBox extends JFrame implements ActionListener, ItemListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private String right = "src/org/cust/test6/img/right.png";
private String wrong = "src/org/cust/test6/img/right.png";
private JCheckBox jcb1 = new JCheckBox("Pencil--10");
private JCheckBox jcb2 = new JCheckBox("Pen--20");
private JCheckBox jcb3 = new JCheckBox("Knife--30");
private JLabel jlb1 = new JLabel("Total:");
private JTextField jtf = new JTextField();
private JButton jb1 = new JButton("Clear");
private JPanel jp1 = new JPanel();
private JPanel jp2 = new JPanel();
private int sum = 0;
private int price[] = new int[] { 10, 20, 30 };
public TestJCheckBox() {
jcb1.setFont(new java.awt.Font("楷书", 1, 30));
jcb2.setFont(new java.awt.Font("楷书", 1, 30));
jcb3.setFont(new java.awt.Font("楷书", 1, 30));
jlb1.setFont(new java.awt.Font("楷书", 1, 30));
jb1.setFont(new java.awt.Font("楷书", 1, 30));
jtf.setFont(new java.awt.Font("楷书", 1, 30));
jcb1.addItemListener(this);
jcb2.addItemListener(this);
jcb3.addItemListener(this);
jb1.addActionListener(this);
jp1.add(jcb1);
jp1.add(jcb2);
jp1.add(jcb3);
jp2.add(jlb1);
jp2.add(jtf);
jp2.add(jb1);
jtf.setPreferredSize(new Dimension(200, 50));
this.add(jp1);
this.add(jp2);
this.setLayout(new GridLayout(2, 3));
this.setTitle("TestJCheckBox");
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setSize(600, 300);
this.setResizable(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand() == "Clear") {
jtf.setText("");
jcb1.setSelected(false);
jcb2.setSelected(false);
jcb3.setSelected(false);
}
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
JCheckBox jcb = (JCheckBox) e.getItem();
if (jcb.isSelected()) {
jcb.setIcon(new ImageIcon(this.right));
} else {
jcb.setIcon(new ImageIcon(this.wrong));
}
System.out.println("-------------");
boolean b[] = new boolean[3];
b[0] = jcb1.isSelected();
b[1] = jcb2.isSelected();
b[2] = jcb3.isSelected();
this.sum = 0;
for (int i = 0; i < b.length; i++) {
if (b[i]) {
this.sum += this.price[i];
}
}
jtf.setText(this.sum + "");
System.out.println("choose1:" + b[0]);
System.out.println("choose2:" + b[1]);
System.out.println("choose3:" + b[2]);
}
public static void main(String[] args) {
TestJCheckBox tjb = new TestJCheckBox();
}
}
效果图:
点击Clear后:
PS:
图中的勾与叉是图片。另外图片路径与格式需正确对应
right.png
wrong.png
5、
package org.cust.test6;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
public class Test_1 extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static int TEXT_ROWS = 8;
private static int TEXT_COLUMS = 20;
private static int upperL;
private static int lowerL;
private static int space;
private static int number;
private static int other;
// private static byte[] fbyt;
private static JFileChooser jfc = new JFileChooser();
private static File file = null;
private static String str = null;
private static char[] strArray1;
private static char[] strArray2;
private static char[] strArray3;
private static JButton jb1 = new JButton("选择文件");
private static JLabel jlb1 = new JLabel("文件导入:");
private static JLabel jlb2 = new JLabel("手工输入框:");
final JTextArea textarea = new JTextArea(TEXT_ROWS, TEXT_COLUMS);
private static JLabel jlb3 = new JLabel("处理结果如下");
private static JLabel jlb4 = new JLabel("大写字母:");
private static JLabel jlb5 = new JLabel("小写字母:");
private static JLabel jlb6 = new JLabel("空 格:");
private static JLabel jlb7 = new JLabel("数 字:");
private static JLabel jlb8 = new JLabel("其他字符:");
private static JTextField jtf1 = new JTextField();
private static JTextField jtf2 = new JTextField();
private static JTextField jtf3 = new JTextField();
private static JTextField jtf4 = new JTextField();
private static JTextField jtf5 = new JTextField();
private static JPanel northjpanel = new JPanel();
private static JPanel southjpanel = new JPanel();
public Test_1() {
jb1.setFont(new java.awt.Font("楷书", 1, 30));
jb1.addActionListener(this);
jlb1.setFont(new java.awt.Font("楷书", 1, 30));
jlb2.setFont(new java.awt.Font("楷书", 3, 40));
jlb3.setFont(new java.awt.Font("楷书", 3, 40));
jlb4.setFont(new java.awt.Font("楷书", 1, 30));
jlb5.setFont(new java.awt.Font("楷书", 1, 30));
jlb6.setFont(new java.awt.Font("楷书", 1, 30));
jlb7.setFont(new java.awt.Font("楷书", 1, 30));
jlb8.setFont(new java.awt.Font("楷书", 1, 30));
jtf1.setFont(new java.awt.Font("楷书", 1, 30));
jtf2.setFont(new java.awt.Font("楷书", 1, 30));
jtf3.setFont(new java.awt.Font("楷书", 1, 30));
jtf4.setFont(new java.awt.Font("楷书", 1, 30));
jtf5.setFont(new java.awt.Font("楷书", 1, 30));
final JTextField textfield = new JTextField();
textfield.setPreferredSize(new Dimension(600, 20));
textarea.getDocument().addDocumentListener(new textfielsListener("txt"));
textfield.setFont(new java.awt.Font("楷书", 1, 40));
northjpanel.setPreferredSize(new Dimension(900, 200));
northjpanel.setLayout(new GridLayout(2, 1));
northjpanel.add(jlb1);
northjpanel.add(jb1);
northjpanel.add(jlb2);
southjpanel.setPreferredSize(new Dimension(900, 400));
southjpanel.setLayout(new GridLayout(6, 2));
// Border tb2 = BorderFactory.createTitledBorder("识别分类如下:");
// southjpanel.setBorder(tb2);
// southjpanel.setToolTipText("识别处理结果如下:");
southjpanel.add(jlb4);
southjpanel.add(jtf1);
southjpanel.add(jlb5);
southjpanel.add(jtf2);
southjpanel.add(jlb6);
southjpanel.add(jtf3);
southjpanel.add(jlb7);
southjpanel.add(jtf4);
southjpanel.add(jlb8);
southjpanel.add(jtf5);
textarea.setPreferredSize(new Dimension(900, 400));
textarea.setFont(new java.awt.Font("楷书", 1, 60));
JScrollPane scrollpane = new JScrollPane(textarea);
scrollpane.setPreferredSize(new Dimension(900, 400));
this.add(northjpanel, BorderLayout.NORTH);
this.add(scrollpane, BorderLayout.CENTER);
this.add(southjpanel, BorderLayout.SOUTH);
this.setResizable(true);
this.setVisible(true);
this.setSize(900, 1000);
this.setLocationRelativeTo(null);
this.setTitle("字符串输入处理");
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand() == "选择文件") {
number = 0;
lowerL = 0;
upperL = 0;
space = 0;
// jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
// jfc.setMultiSelectionEnabled(false);
jfc.setCurrentDirectory(new File("."));
jfc.setFileFilter(new textfielsListener("txt"));
int i = jfc.showOpenDialog(null);
if (i == JFileChooser.APPROVE_OPTION) {
file = jfc.getSelectedFile();
System.out.println(file.getAbsolutePath());
textarea.setText("");
}
try {
InputStream is = new FileInputStream(file);
byte[] fbyt = new byte[is.available()];
is.read(fbyt);
System.out.println("文本内容:" + new String(fbyt));
String fstr = new String(fbyt);
char strArray1[] = fstr.toCharArray();
for (int j = 0; j < strArray1.length; j++) {
if (strArray1[j] >= '0' && strArray1[j] <= '9') {
number++;
} else if (strArray1[j] >= 'a' && strArray1[j] <= 'z') {
lowerL++;
} else if (strArray1[j] >= 'A' && strArray1[j] <= 'Z') {
upperL++;
} else if (strArray1[j] == ' ') {
space++;
}
}
other = strArray1.length - number - lowerL - upperL - space;
System.out.println("文本中字符串长度:" + strArray1.length);
jtf1.setText(upperL + "");
jtf2.setText(lowerL + "");
jtf3.setText(space + "");
jtf4.setText(number + "");
jtf5.setText(other + "");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public class textfielsListener extends FileFilter implements DocumentListener {
private String suffix;
@Override
public void removeUpdate(DocumentEvent e) {
System.out.println("执行操作:remove");
upperL = 0;
lowerL = 0;
space = 0;
number = 0;
other = 0;
try {
str = null;
str = e.getDocument().getText(0, e.getDocument().getLength());
strArray1 = str.toCharArray();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
for (int i = 0; i < str.length(); i++) {
if (strArray2[i] >= '0' && strArray2[i] <= '9') {
number++;
} else if (strArray2[i] >= 'a' && strArray2[i] <= 'z') {
lowerL++;
} else if (strArray2[i] >= 'A' && strArray2[i] <= 'Z') {
upperL++;
} else if (strArray2[i] == ' ') {
space++;
}
}
other = str.length() - number - lowerL - upperL - space;
System.out.println(str.length());
jtf1.setText(upperL + "");
jtf2.setText(lowerL + "");
jtf3.setText(space + "");
jtf4.setText(number + "");
jtf5.setText(other + "");
}
@Override
public void insertUpdate(DocumentEvent e) {
System.out.println("执行操作:insert");
upperL = 0;
lowerL = 0;
space = 0;
number = 0;
other = 0;
try {
// str =
// e.getDocument().getText(e.getDocument().getStartPosition().getOffset(),
// e.getDocument().getLength())
str = null;
str = e.getDocument().getText(0, e.getDocument().getLength());
strArray2 = str.toCharArray();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
for (int i = 0; i < strArray2.length; i++) {
if (strArray2[i] >= '0' && strArray2[i] <= '9') {
number++;
} else if (strArray2[i] >= 'a' && strArray2[i] <= 'z') {
lowerL++;
} else if (strArray2[i] >= 'A' && strArray2[i] <= 'Z') {
upperL++;
} else if (strArray2[i] == ' ') {
space++;
}
}
other = str.length() - number - lowerL - upperL - space;
System.out.println("输入字符串长度:" + str.length());
jtf1.setText(upperL + "");
jtf2.setText(lowerL + "");
jtf3.setText(space + "");
jtf4.setText(number + "");
jtf5.setText(other + "");
}
@Override
public void changedUpdate(DocumentEvent e) {
}
public textfielsListener() {
}
public textfielsListener(String suffix) {
this.suffix = suffix;
}
@Override
public boolean accept(File f) {
// TODO Auto-generated method stub
if (f.getName().endsWith(".txt") || f.isDirectory()) {
return true;
}
return false;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return "文本文档(*.txt)";
}
}
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
Test_1 test = new Test_1();
}
});
}
}
效果图:
输入:
删除:
文件选择:
确认选择: