Java生肖查询
发布网友
发布时间:2022-06-08 11:38
我来回答
共1个回答
热心网友
时间:2023-11-23 11:50
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Year extends JFrame implements Serializable{
private static final long serialVersionUID=21L;
private JTextField jt;
private JButton jb;
private JLabel ab1,ab2;
private JPanel jp1;
Year(){
this.setTitle("生肖查询小工具");
this.setBounds(400,300,300,200);
this.setLayout(new GridLayout(3,1));
init();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
private void init() {
jp1=new JPanel();
jt=new JTextField(10);
jb=new JButton("查询:");
ab1=new JLabel();
ab2=new JLabel("输入:");
ab1.setSize(50, 20);
ab1.setOpaque(true);
ab1.setForeground(Color.RED);
ab1.setBackground(Color.ORANGE);
ab1.setHorizontalAlignment(0);
ab1.setVerticalAlignment(0);
event();
jp1.add(ab2);
jp1.add(jt);
this.add(jp1);
this.add(ab1);
this.add(jb);
}
private void event() {
jt.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyChar()<48||e.getKeyChar()>57) {
e.consume();
}
}
});
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String str=jt.getText();
String src=getYear(Integer.parseInt(str));
ab1.setText(str+"\t:"+src);
jt.setText(null);
jt.requestFocus();
}
});
}
public static void main(String[] args) {
new Year();
}
public String getYear(int year) {
if (year < 1900) {
return "未知";
}
int start = 1900;
String[] years = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
return years[(year - start) % years.length];
}
}