Java 由浅入深GUI编程实战练习
项目简介:
1.实现利用下拉菜单的方式选择发送快捷语句;
2.实现对留言信息内容的置顶处理以及至尾处理;
3.实现清屏处理或现实保留部分留言内容;
运行界面:
代码展示:
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Choice; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Demo4 { // 测试 public static void main(String[] args) { MessageBoard mb = new MessageBoard(); mb.go(); } } class MessageBoard { Frame f; WindowAdapter w; TextArea center; Label la1, la2, la3; Panel east, south, north; Button b1, b2, b3, b4; Choice l1; TextField t1; // 构造函数 MessageBoard() { f = new Frame("留言板"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { f.setVisible(false); System.exit(0); } }); f.setBounds(0, 0, 600, 400); f.setLayout(new BorderLayout()); f.setResizable(false); north = new Panel(); south = new Panel(); east = new Panel(); center = new TextArea("留言内容:"); center.setEditable(false); b1 = new Button("清屏"); b2 = new Button("至顶"); b3 = new Button("至尾"); la1 = new Label("留言版"); la2 = new Label("你"); la3 = new Label(" 地说:"); t1 = new TextField(20); b4 = new Button("提交"); l1 = new Choice(); l1.add("微笑 "); l1.add("生气 "); l1.add("伤心 "); } public void go() { f.add(BorderLayout.NORTH, north); f.add(BorderLayout.SOUTH, south); f.add(BorderLayout.EAST, east); f.add(BorderLayout.CENTER, center); north.add(BorderLayout.CENTER, la1); south.add(la2); south.add(l1); south.add(la3); south.add(t1); south.add(b4); east.setLayout(new GridLayout(9, 0, 1, 10)); east.add(b1); east.add(b2); east.add(b3); f.setVisible(true); b4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text1, text2; text1 = l1.getSelectedItem(); text2 = t1.getText(); t1.setText(null); if (t1.getText() != "") { center.append("\n"); center.append(text1); center.append(text2); } } }); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { center.setText("留言内容:"); } }); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { center.requestFocusInWindow(); center.setCaretPosition(8); } }); b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { center.requestFocusInWindow(); center.setCaretPosition(center.getText().length()); } }); } }
一,项目简介
1.利用Java GUI 绘制图像界面,设置整体布局
2.编写一个随机数生成1~100的随机数
3.编写一个验证类,用于验证用户输入值与生成随机数是否相等并记录用户猜测次数,当用户猜测成功或者超过5次结束游戏
二,运行界面
三,代码实现
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Demo5 extends JFrame implements ActionListener { JPanel p1; JButton btn1, btn2; JLabel jb1, jb2, jb3; JLabel Haiamge; JTextField text; JTextArea area; ImageIcon image; ImageIcon image1 = new ImageIcon("img/1.jpg"), image2 = new ImageIcon("img/2.jpg"), image3 = new ImageIcon("img/3.jpg"), image4 = new ImageIcon("img/4.gif"); int number; boolean flat = false;// 是否生成随机数 // 构造函数 public Demo5() { setTitle("我的猜字游戏"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); setLayout(null);// 先设置为null,不然不显示 setSize(400, 300); setLocation(30, 30); getContentPane().setBackground(Color.GRAY);// 一定要加getContentPane p1 = new JPanel(); p1.setBackground(Color.LIGHT_GRAY); p1.setBounds(0, 0, 320, 100); p1.setLayout(null); add(p1); btn1 = new JButton("生成随机数"); btn1.setBounds(200, 20, 100, 25); btn1.addActionListener(this); p1.add(btn1); btn2 = new JButton("确定"); btn2.setBounds(200, 50, 100, 25); btn2.addActionListener(this); p1.add(btn2); jb1 = new JLabel("选择一个随机数"); jb1.setForeground(Color.BLUE); jb1.setBounds(40, 20, 110, 23); p1.add(jb1); jb2 = new JLabel("然后输入推测数字(1~100)"); jb2.setForeground(Color.BLUE); jb2.setBounds(20, 35, 150, 23); p1.add(jb2); text = new JTextField("0"); text.setForeground(Color.magenta); text.setBounds(40, 60, 110, 23); p1.add(text); jb3 = new JLabel("未生成随机数"); jb3.setForeground(Color.red); jb3.setBackground(Color.gray); jb3.setBounds(20, 160, 120, 23); add(jb3); area = new JTextArea("我猜!我猜!我猜猜猜!"); area.setForeground(Color.green); area.setBackground(Color.gray); area.setFont(new Font("宋体", Font.BOLD, 13)); area.setEditable(false); area.setBounds(20, 130, 150, 25); add(area); Haiamge = new JLabel(); Haiamge.setBounds(180, 101, 128, 128); add(Haiamge); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == btn1) { number = (int) (Math.random() * 10) + 1; jb3.setText("已生成随机数"); area.setText("猜"); Haiamge.setIcon(image2); flat = true;// 生成随机数 } else if (e.getSource() == btn2) { int guess = 0; try { guess = Integer.parseInt(text.getText()); if (flat == false) { area.setText("失败"); return; } else { if (guess == number) { area.setText(" 猜对了!就是" + number); flat = false; jb3.setText("未生成随机数"); Haiamge.setIcon(image1); } else if (guess > number) { area.setText(" 猜大了!"); text.setText(null); Haiamge.setIcon(image3); } else if (guess < number) { area.setText("猜小了!"); text.setText(null); Haiamge.setIcon(image4); } } } catch (NumberFormatException event) { event.printStackTrace(); } } } public static void main(String[] args) { Demo5 dem = new Demo5(); dem.setVisible(true); } }
补充 我的注意事项:
一,項目介紹
1.可以查看年,月,日等功能。能获取今天的日期,并且能够通过下拉年,月的列表。
2.当程序运行时,显示的时间是系统当前时间。
3.可以手动输入时间,确定后系统跳转到制定的时间。
4.提供一种点击功能,通过点击实现年份,月份的自增和自减功能。
二,运行界面
代码:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class Demo6 extends JApplet { private static final long serialVersionUID = 1L; public static final String WEEK_SUN = "SUN"; public static final String WEEK_MON = "MON"; public static final String WEEK_TUE = "TUE"; public static final String WEEK_WED = "WED"; public static final String WEEK_THU = "THU"; public static final String WEEK_FRI = "FRI"; public static final String WEEK_SAT = "SAT"; public static final Color background = Color.white; public static final Color foreground = Color.black; public static final Color headerBackground = Color.blue; public static final Color headerForeground = Color.white; public static final Color selectedBackground = Color.blue; public static final Color selectedForeground = Color.white; private JPanel cPane; private JLabel yearsLabel; private JSpinner yearsSpinner; private JLabel monthsLabel; private JComboBox<Integer> monthsComboBox; private JTable daysTable; private AbstractTableModel daysModel; private Calendar calendar; public Demo6() { cPane = (JPanel) getContentPane(); } public void init() { cPane.setLayout(new BorderLayout()); calendar = Calendar.getInstance(); yearsLabel = new JLabel("Year: "); yearsSpinner = new JSpinner(); //利用编辑器 yearsSpinner.setEditor(new JSpinner.NumberEditor(yearsSpinner, "0000")); yearsSpinner.setValue(new Integer(calendar.get(Calendar.YEAR))); yearsSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.YEAR, ((Integer) yearsSpinner.getValue()).intValue()); int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day > maxDay ? maxDay : day); updateView(); } }); JPanel yearMonthPanel = new JPanel(); cPane.add(yearMonthPanel, BorderLayout.NORTH); yearMonthPanel.setLayout(new BorderLayout()); yearMonthPanel.add(new JPanel(), BorderLayout.CENTER); JPanel yearPanel = new JPanel(); yearMonthPanel.add(yearPanel, BorderLayout.WEST); yearPanel.setLayout(new BorderLayout()); yearPanel.add(yearsLabel, BorderLayout.WEST); yearPanel.add(yearsSpinner, BorderLayout.CENTER); monthsLabel = new JLabel("Month: "); monthsComboBox = new JComboBox<Integer>(); for (int i = 1; i <= 12; i++) { monthsComboBox.addItem(new Integer(i)); } monthsComboBox.setSelectedIndex(calendar.get(Calendar.MONTH)); monthsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.MONTH, monthsComboBox.getSelectedIndex()); int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day > maxDay ? maxDay : day); updateView(); } }); JPanel monthPanel = new JPanel(); yearMonthPanel.add(monthPanel, BorderLayout.EAST); monthPanel.setLayout(new BorderLayout()); monthPanel.add(monthsLabel, BorderLayout.WEST); monthPanel.add(monthsComboBox, BorderLayout.CENTER); daysModel = new AbstractTableModel() { /** * */ private static final long serialVersionUID = -3517455337953024330L; public int getRowCount() { return 7; } public int getColumnCount() { return 7; } public Object getValueAt(int row, int column) { if (row == 0) { return getHeader(column); } row--; Calendar calendar = (Calendar) Demo6.this.calendar.clone(); calendar.set(Calendar.DAY_OF_MONTH, 1); int dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); int moreDayCount = calendar.get(Calendar.DAY_OF_WEEK) - 1; int index = row * 7 + column; int dayIndex = index - moreDayCount + 1; if (index < moreDayCount || dayIndex > dayCount) { return null; } else { return new Integer(dayIndex); } } }; daysTable = new CalendarTable(daysModel, calendar); daysTable.setCellSelectionEnabled(true); daysTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); daysTable.setDefaultRenderer(daysTable.getColumnClass(0), new TableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { String text = (value == null) ? "" : value.toString(); JLabel cell = new JLabel(text); cell.setOpaque(true); if (row == 0) { cell.setForeground(headerForeground); cell.setBackground(headerBackground); } else { if (isSelected) { cell.setForeground(selectedForeground); cell.setBackground(selectedBackground); } else { cell.setForeground(foreground); cell.setBackground(background); } } return cell; } }); updateView(); cPane.add(daysTable, BorderLayout.CENTER); } public static String getHeader(int index) { switch (index) { case 0: return WEEK_SUN; case 1: return WEEK_MON; case 2: return WEEK_TUE; case 3: return WEEK_WED; case 4: return WEEK_THU; case 5: return WEEK_FRI; case 6: return WEEK_SAT; default: return null; } } public void updateView() { daysModel.fireTableDataChanged(); daysTable.setRowSelectionInterval(calendar.get(Calendar.WEEK_OF_MONTH), calendar.get(Calendar.WEEK_OF_MONTH)); daysTable.setColumnSelectionInterval(calendar.get(Calendar.DAY_OF_WEEK) - 1, calendar.get(Calendar.DAY_OF_WEEK) - 1); } public static class CalendarTable extends JTable { private static final long serialVersionUID = 1L; private Calendar calendar; public CalendarTable(TableModel model, Calendar calendar) { super(model); this.calendar = calendar; } public void changeSelection(int row, int column, boolean toggle, boolean extend) { super.changeSelection(row, column, toggle, extend); if (row == 0) { return; } Object obj = getValueAt(row, column); if (obj != null) { calendar.set(Calendar.DAY_OF_MONTH, ((Integer)obj).intValue()); } } } public static void main(String[] args) { JFrame frame = new JFrame("Calendar Application"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Demo6 myCalendar = new Demo6(); myCalendar.init(); frame.getContentPane().add(myCalendar); frame.setSize(240, 172); } }