Java大一的题目求大神帮忙看看怎么写TAT求源代码

编写 GUI 程序满足以下要求。① 编写自定义异常类 WrongDateException,以描述错误的日期字符串,如 2011-10-32、2013-02-31 等。② 编写一个 convert 方法将文本框中的字符串(约定以“4 位年-2 位月-2 位 日”的格式)转换为日期(java.util.Date)对象,并在点击转换按钮时调用该方法。③ 若转换成功,则将得到的日期对象以“XXXX 年 XX 月 XX 日”的格式作为窗口下部标签的内容。④ 若转换失败,则 convert 方法抛出 WrongDateException 异常。⑤ 在调用 convert 方法的方法中捕获 WrongDateException 异常,并在下部标签中呈现该异常信息。提示:使用 java.text.SimpleDateFormat 类及其 setLenient、parse、format 等方法。

第1个回答  2020-05-02

哈哈~网上很多哈,GUI我也不会,现学现卖一个



package swing;

import javafx.embed.swing.JFXPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @author wenxy
* @create 2020-05-01
*/
public class JavaFxDate {

public static void main(String[] args) {
// 创建 JFrame 实例
JFrame frame = new JFrame();
// Setting the width and height of frame
frame.setSize(310, 180);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/* 创建面板,这个类似于 HTML 的 div 标签
* 我们可以创建多个面板并在 JFrame 中指定位置
* 面板中我们可以添加文本字段,按钮及其他组件。
*/
JPanel panel = new JPanel();
// 添加面板
frame.add(panel);
/*
* 调用用户定义的方法并添加组件到面板
*/
placeComponents(panel);

// 设置界面可见
frame.setVisible(true);
}

private static void placeComponents(JPanel panel) {

/* 布局部分我们这边不多做介绍
* 这边设置布局为 null
*/
panel.setLayout(null);

// 创建 JLabel
JLabel userLabel = new JLabel("请输入日期字符串");
userLabel.setBounds(5, 5, 300, 25);
panel.add(userLabel);

/*
* 创建文本域用于用户输入
*/
JTextField userText = new JTextField(20);
userText.setBounds(5, 40, 200, 25);
panel.add(userText);

// 创建 JLabel
JLabel showLable = new JLabel();
showLable.setBounds(5, 70, 300, 25);
panel.add(showLable);


// 创建登录按钮
JButton loginButton = new JButton("转换");
loginButton.setBounds(180, 40, 100, 25);
loginButton.addActionListener(new ActionListener() {
DateFormat input = new SimpleDateFormat("yyyy-MM-dd");
DateFormat output = new SimpleDateFormat("yyyy年MM月dd日");

{
input.setLenient(false);    // 设置严格按格式匹配
output.setLenient(false);
}

@Override
public void actionPerformed(ActionEvent actionEvent) {
try {
Date date = convert(userText.getText());
showLable.setText("成功:" + output.format(date));
showLable.setForeground(Color.GREEN);
} catch (WrongDateException e) {
showLable.setText(e.getMessage());
showLable.setForeground(Color.RED);
}
}

private Date convert(String text) throws WrongDateException {
try {
return input.parse(text);
} catch (ParseException e) {
throw new WrongDateException(text);
}
}

});
panel.add(loginButton);
}

static class WrongDateException extends Exception {
WrongDateException(String s) {
super(s + "不是合法的日期字符串");
}
}

}

本回答被提问者采纳
相似回答