Java Swing单击文本框弹出日历组件

合集下载

java 弹窗方法

java 弹窗方法

java 弹窗方法Java作为一种广泛应用于各种领域的编程语言,提供了丰富的图形用户界面(GUI)组件。

在Java中,弹窗是一种常见的交互方式,可以用来提示用户、获取用户输入或显示信息。

本文将介绍Java弹窗方法的分类、原理以及常见组件的使用方法,并通过实例进行演示。

一、弹窗方法的概述在Java中,弹窗方法主要有两种:1.自带弹窗:Java自带的Swing和JavaFX库提供了许多弹窗组件,如JOptionPane的showMessageDialog、showInputDialog等。

2.自定义弹窗:通过Java的图形界面组件(如JFrame、JDialog等)和事件处理机制来实现。

二、Java弹窗方法的分类与原理1.自带弹窗Java自带的弹窗方法主要位于JOptionPane库中。

这些方法可以方便地创建各种类型的对话框,如信息提示框、输入框等。

以下是几个常用的自带弹窗方法:- showMessageDialog(parent,message,title,buttons):显示一个带有指定信息、标题和按钮的对话框。

- showInputDialog(parent,message,title,defaultValue):显示一个带有指定信息、标题和默认值的输入框。

- showConfirmDialog(parent,message,title,options):显示一个带有指定信息、标题和选项的确认对话框。

2.自定义弹窗自定义弹窗是通过创建JFrame或JDialog组件来实现。

首先创建一个包含弹窗内容的JPanel,然后设置JPanel的边界约束,最后添加到JFrame或JDialog中。

以下是自定义弹窗的简单示例:```javaJFrame frame = new JFrame("自定义弹窗");frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);frame.setSize(300, 200);JPanel panel = new JPanel();panel.setLayout(new BorderLayout());JLabel label = new JLabel("请输入姓名:");JTextField textField = new JTextField(20);panel.add(label, BorderLayout.WEST);panel.add(textField, BorderLayout.EAST);frame.getContentPane().add(panel);frame.setVisible(true);```三、常见Java弹窗组件及使用方法1.JFrame:创建一个独立的窗口,可以设置大小、标题和关闭操作等。

java 弹窗方法

java 弹窗方法

java 弹窗方法在过去的学习和工作中,我们可能会遇到各种各样的弹窗需求,如消息提示、窗口交互等。

Java作为一种广泛应用于企业级开发的编程语言,提供了多种弹窗方法。

本文将为您介绍Java弹窗方法的分类与原理,常见Java弹窗工具箱,并通过实例演示与代码解析,帮助您更好地理解和应用这些弹窗方法。

1.弹窗方法的概述在Java中,弹窗方法主要包括两类:自带弹窗和自定义弹窗。

自带弹窗是由Java自带的Swing组件库提供的,如JOptionPane类的showMessageDialog、showInputDialog等方法。

自定义弹窗则是通过Java 编写界面组件来实现,如使用JavaFX、Swing等框架创建窗口。

2.Java弹窗方法的分类与原理(1)自带弹窗Java自带的弹窗方法主要位于JOptionPane类中,包括以下几种:- showMessageDialog:显示一个包含指定消息的对话框。

- showInputDialog:显示一个包含指定消息和输入框的对话框,用户可以输入内容并确认。

- showConfirmDialog:显示一个包含指定消息的确认对话框,用户可以选择“是”或“否”。

- showOptionDialog:显示一个包含指定消息的选择对话框,用户可以从多个选项中选择一个。

(2)自定义弹窗自定义弹窗主要是通过Java编写界面组件来实现,常见的有以下几种方法:- 使用JavaFX:通过JavaFX框架创建窗口、按钮、文本框等组件,搭建需要的弹窗界面。

- 使用Swing:通过Swing框架创建窗口、按钮、文本框等组件,搭建需要的弹窗界面。

- 使用第三方库:如使用Electron、React Native等库实现跨平台弹窗。

3.常见Java弹窗工具箱介绍在Java中,有一些开源的弹窗工具箱可以帮助我们快速搭建弹窗界面,如下:- Apache APR:一个基于Java的弹窗组件库,提供了丰富的弹窗样式和功能。

JavaSwing日历控件

JavaSwing日历控件

Java swing日历控件,界面精美,使用方便,能用于个人作品首先,声明一点,这个控件是我从一套据说价值九百多美元的swing类包中提取出来,并加以修改的,所以:
一,你不能把该控件用于任何商业产品中。

二,该控件没有源代码。

(DatePicker.java除外,这个是我加进去的)
三,该控件可以用于你的个人作品中。

截图如下:
使用之前请把datepicker.jar导入classpath中
使用方法如下:
DatePicker datepick = new DatePicker();
或者
datepick = new DatePicker(date,DefaultFormat,font,dimension);//自定义参数值
//各参数含义如下
//参数1 设置该控件的初始值(可选)
//参数2 设置日期的格式(可选)
//参数3 设置该控件的字体(可选)
//参数3 设置该控件的大小(可选)
//该控件继承自JComponent ,它继承了Jcomponent的属性
datepick.setTimePanleVisible(true);//设置时钟面板可见
atepick.setHightlightdays(hilightDays, Color.red);//设置一个月份中需要高亮显示的日子
datepick.setDisableddays(disabledDays);//设置一个月份中不需要的日子,呈灰色显示。

java jpopupmenu方法 -回复

java jpopupmenu方法 -回复

java jpopupmenu方法-回复Java JPopupMenu方法是Java Swing库中的一种组件,它提供了弹出菜单的功能。

在本文中,我们将一步一步地回答有关JPopupMenu的问题,并深入讨论其使用方法和示例。

1. 什么是JPopupMenu?JPopupMenu是Java Swing库中的一个类,它表示弹出菜单。

它是一个轻量级组件,可以在鼠标右键单击或其他用户交互方式触发时出现。

JPopupMenu可以包含菜单项、子菜单和分隔符。

2. 如何创建和显示JPopupMenu?要创建JPopupMenu,我们可以使用其默认构造函数:javaJPopupMenu popupMenu = new JPopupMenu();要显示JPopupMenu,我们可以通过以下方法将其与组件关联:javacomponent.setComponentPopupMenu(popupMenu);其中,component是指定的组件,可以是任何Swing组件,例如JButton或JTextField。

当用户右键单击该组件时,JPopupMenu将出现。

3. 如何向JPopupMenu添加菜单项?我们可以使用JPopupMenu的add()方法添加菜单项:javaJMenuItem menuItem = new JMenuItem("菜单项标签"); popupMenu.add(menuItem);在上面的示例中,我们创建了一个名为"菜单项标签"的菜单项,并将其添加到JPopupMenu中。

可以通过添加多个菜单项来构建弹出菜单。

4. 如何向JPopupMenu添加子菜单?与添加菜单项类似,我们可以使用JPopupMenu的add()方法添加子菜单:javaJMenu submenu = new JMenu("子菜单标签");popupMenu.add(submenu);在上面的示例中,我们创建了一个名为"子菜单标签"的子菜单,并将其添加到JPopupMenu中。

java日历小程序

java日历小程序

java日历小程序简介:Java日历小程序是一个基于Java语言开发的工具,用于显示和管理日期和时间。

它提供了一种简单而直观的方式来查看、创建和编辑日历事件,并提供了一些额外的功能,如提醒、重复事件和时间段的计算等。

本文将详细介绍Java日历小程序的功能、使用方法和设计原理。

功能:1. 显示日历:Java日历小程序可以显示当前月份的日历,并以日、周或月的形式展示。

用户可以通过界面上的上下翻页按钮切换月份,方便查看不同日期的日历。

2. 创建和编辑事件:用户可以通过Java日历小程序创建新的日历事件,并为每个事件指定标题、日期、时间和地点等详细信息。

程序还提供了事件编辑功能,允许用户修改已有事件的信息。

3. 提醒功能:Java日历小程序可以设置事件的提醒功能,提醒用户在指定的时间前提醒。

用户可以选择在事件开始前几分钟、几小时或几天提醒,并可以自定义提醒方式,如弹窗、声音或邮件通知等。

4. 重复事件:用户可以为事件设置重复功能,使事件在指定的日期间隔内重复发生。

可以选择每天、每周、每月或每年重复,并可以设置重复的结束日期。

5. 时间段计算:Java日历小程序可以计算两个日期之间的时间段,如计算两个事件之间的天数、小时数或分钟数等。

用户可以选择计算方式,并获取精确的时间段结果。

使用方法:1. 下载和安装:用户可以从官方网站上下载Java日历小程序的安装包,然后按照安装向导进行安装。

安装完成后,用户可以在桌面或开始菜单中找到程序的快捷方式。

2. 打开程序:双击程序的快捷方式,Java日历小程序将启动并显示当前月份的日历。

用户可以通过界面上的按钮和菜单来使用各种功能。

3. 创建事件:用户可以点击界面上的“添加事件”按钮,弹出一个对话框,输入事件的详细信息,如标题、日期、时间和地点等。

点击“确定”按钮后,事件将被创建并显示在日历上。

4. 编辑事件:用户可以在日历上点击已有的事件,弹出一个对话框,允许用户修改事件的信息。

java课程设计简单日历(word文档良心出品)

java课程设计简单日历(word文档良心出品)

j a v a课程设计报告题目:JA V A简易时间日历程序****:***学号:**********专业班级:信101****:***课程设计题目题目说明通过编写一个基于JAVA的应用系统综合实例,自定义一个日历组件显示日期和时间并进行适当的功能扩充,实践Java语言编程技术。

系统设计1 设计目标一个完整的程序应具有以下功能:1)显示当月日历、当前日期、当前时间;2)可查寻任意月以及任意年的日历;3)使用图形化界面能够弹出对话框;5)正常退出程序。

2 设计思想设计一个类用来构成日历系统的主窗口,然后编写一个框架类显示时间和提示信息。

在设计中应用了多种容器和控件。

系统模块划分图1:简易日历的程序结构图初始化:public void init()完成界面初始化,形成一个以挂历形式显示当前日期的窗口。

日历描述:(1)public void updateView()改变日期后完成更新界面;(2)抽象类java.util.Calendar获取系统日期并传递日期数据而且在人工改变日期后得出当天是周几;(3)public static void main(String[] args)主函数完成系统各算法的调用并对主窗口的一些属性进行设置;滚动时间:将时间以文本的形式在文本框中滚动播出,并能改变滚动的速度。

4. 使用类及接口仅仅简单说明类的功能,详细资料请参看《JavaTM 2 Platform Standard Ed. 6》的电子文档,常规的接口与包则省略不屑。

//以下是日历程序块中使用的类package fancy;import java.awt.*;import java.awt.event.*;import java.util.*; //主要用此包中的日期和时间类import javax.swing.*;import javax.swing.event.*;import javax.swing.table.*;//以下是对滚动时间程序块所使用的类和接口,用到定时器类Timerimport java.awt.Color;import java.awt.FlowLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.FocusListener;、//用于监听鼠标单击(焦点改变)事件import java.awt.event.FocusEvent;//用于响应鼠标单击(焦点改变)事件、import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.JSpinner;//让用户从一个有序序列中选择一个数字或者一个对象值的单行输入字段。

SWT实现弹出日历控件

SWT实现弹出日历控件

SWT实现弹出日历控件SWT实现弹出日历控件2010-08-25 10:01:48| 分类:Eclipse 插件开发|字号订阅实现像网页上的那种用户单击一个Text框然后框下面出现一个日历控件,点击Text框以外的地方日历消失,怎么实现?Java代码import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; importorg.eclipse.swt.graphics.Color; importorg.eclipse.swt.graphics.Point; importorg.eclipse.swt.widgets.Display; importorg.eclipse.swt.widgets.Shell; importorg.eclipse.swt.widgets.Text; public class DateTimeDemo extends Shell { private static Display display; private Text text;public static void main(String args[]){ try { display =Display.getDefault(); DateTimeDemo shell = new DateTimeDemo(display, SWT.SHELL_TRIM); shell.open(); yout();while(!shell.isDisposed()){ if(!display.readAndDispatch()){ display.sleep();} }display.dispose(); }catch(Exception e){ e.printStackTrace(); } } public DateTimeDemo(Display display, int style) { super(display, style); createContents(); } protected void createContents(){ setText("DateTime");setSize(471, 140); text = new Text(this, SWT.BORDER); text.setEditable(false); text.setBackground(new Color(display, 255, 255, 255)); text.setBounds(122, 41, 228, 25);text.addMouseListener(new MouseAdapter(){ public void mouseUp(MouseEvent e) { DTDialog dialog =DTDialog.getInstance(DateTimeDemo.this);dialog.open(); } }); } public Point getDtLocation() { return new Point(text.getLocation().x +DateTimeDemo.this.getLocation().x,text.getLocation().y + DateTimeDemo.this.getLocation().y + 60); } public void setDate(String str) { text.setText(str); }@Override protected void checkSubclass(){ // Disable the check that prevents subclassing of SWT components } } Java代码import org.eclipse.swt.SWT; importorg.eclipse.swt.events.FocusAdapter; importorg.eclipse.swt.events.FocusEvent; importorg.eclipse.swt.events.SelectionAdapter; importorg.eclipse.swt.events.SelectionEvent; importyout.FillLayout; importorg.eclipse.swt.widgets.DateTime; importorg.eclipse.swt.widgets.Dialog; importorg.eclipse.swt.widgets.Display; importorg.eclipse.swt.widgets.Shell; public class DTDialog extends Dialog { private Objectresult; private Shell shell; private DateTime dateTime; private DateTimeDemo parent; private static DTDialog instance; public static DTDialog getInstance(DateTimeDemo parent) { if(instance == null){ instance = newDTDialog(parent); } return instance; } privateDTDialog(DateTimeDemo parent){ super(parent, SWT.NO_TRIM);this.parent = parent; } public Object open() { if(shell == null ||shell.isDisposed()){ createContents();shell.open(); yout();Display display = getParent().getDisplay();while(!shell.isDisposed()){ if(!display.readAndDispatch()){ display.sleep();} }display.dispose(); } else{ shell.setLocation(parent.getDtLocation()); shell.setVisible(true);shell.setFocus(); } return result; } protected void createContents() { shell = newShell(getParent(), SWT.NO_TRIM);shell.setLayout(new FillLayout());shell.setSize(272, 140);shell.setLocation(parent.getDtLocation());shell.setText("SWT Dialog"); dateTime = new DateTime(shell, SWT.CALENDAR);dateTime.addSelectionListener(new SelectionAdapter() { public voidwidgetSelected(SelectionEvent e){ parent.setDate(formatDt());} });dateTime.addFocusListener(new FocusAdapter(){ public void focusLost(FocusEvent e) { parent.setDate(formatDt()); shell.setVisible(false); } });} private String formatDt(){ return dateTime.getYear() + "-" + dateTime.getMonth() + "-" + dateTime.getDay(); }public Shell getShell() { return shell; } }。

一个java Swing做的日历控件

一个java Swing做的日历控件
//设置列顺序不可改变
tbCalendar .getTableHeader().setResizingAllowed(false);
/////设置列大小不可改变
nowDate=new JLabel();
nowDate.setText("今天是:"+gc.get(Calendar.YEAR)+"年"+
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
if(e.getKeyCode()==KeyEvent.VK_ENTER)
btnYearDown=new JButton("▼");
//年份减按钮
btnYearDown.setFont(font);
btnYearDown.setMargin(new Insets(0,0,0,0));
btnYearUp.setBounds(40, 6, 20, 10);
//按钮定位
btnYearDown.setBounds(40, 16, 20, 10);
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
isSelected, boolean hasFocus,
int row, int column) {
Object o=tbCalendar.getValueAt(row,

swing日期控件

swing日期控件

Swing日期控件一、截图:二、源代码:package com.longtu.rpt.app.view.rptview.multisheet;import java.util.Calendar;import javax.swing.JComboBox;import javax.swing.JTable;import javax.swing.table.DefaultTableModel;public class DateChoiceActive {//初始化年选择下拉框public static String[] initItemsYear(){String[] arrYear = new String[70];for(int i=1980;i<2050;i++){arrYear[i-1980]=String.valueOf(i);}return arrYear;}//初始化月选择下拉框public static void initItemsMonth(JComboBox cmbMonth){cmbMonth.addItem("一月");cmbMonth.addItem("二月");cmbMonth.addItem("三月");cmbMonth.addItem("四月");cmbMonth.addItem("五月");cmbMonth.addItem("六月");cmbMonth.addItem("七月");cmbMonth.addItem("八月");cmbMonth.addItem("九月");cmbMonth.addItem("十月");cmbMonth.addItem("十一月");cmbMonth.addItem("十二月");}public static String initComboboxSelected(int month){if(1 == month){return "一月";}else if(2 == month){return "二月";}else if(3 == month){return "三月";}else if(4 == month){return "四月";}else if(5 == month){return "五月";}else if(6 == month){return "六月";}else if(7 == month){return "七月";}else if(8 == month){return "八月";}else if(9 == month){return "九月";}else if(10 == month){return "十月";}else if(11 == month){return "十一月";}else {return "十二月";}}public static int getSelectItemValue(String month){if("一月".equals(month)){return 1;}else if("二月".equals(month)){return 2;}else if("三月".equals(month)){return 3;}else if("四月".equals(month)){return 4;}else if("五月".equals(month)){return 5;}else if("六月".equals(month)){return 6;}else if("七月".equals(month)){return 7;}else if("八月".equals(month)){return 8;}else if("九月".equals(month)){return 9;}else if("十月".equals(month)){return 10;}else if("十一月".equals(month)){return 11;}else if("十二月".equals(month)){return 12;}return 0;}private static int getCurrentMonthFirstDay(int year,int month){ Calendar now = Calendar.getInstance();now.set(year,month-1,1);int week = now.get(Calendar.DAY_OF_WEEK)-1;return week;}private static int getCurrentMonthDays(int year,int month){int days = 0; // 存储当月的天数boolean isRn = false;//是否闰年for (int i = 1900; i < year; i++) {if (i % 4 == 0 && !(i % 100 == 0) || i % 400 == 0) {isRn = true;} else {}}for (int i = 1; i <= month; i++) {switch (i) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:days = 31;break;case 2:if (isRn) {days = 29;} else {days = 28;} break;default:days = 30; break;}}return days;}public static void updateMonthPanel(JTable table,DefaultTableModel model,int year,int month,Object[] rowData){int week = getCurrentMonthFirstDay(year,month);int totalday = getCurrentMonthDays(year,month);int count = 1;for(int i=0;i<6;i++){model.addRow(rowData);for(int j=0;j<7;j++){if(count>totalday){table.setValueAt("", i, j);}else if(i==0&&week!=0){j = week;table.setValueAt(count, i, j);}else{table.setValueAt(count, i, j);}week = 0;count++;}}}public static String formatDateToString(int year,int month,int date){String day = "";String mon = "";if(date < 10){day = "0"+date;}else{day = ""+date;}if(month < 10){mon = "0"+month;}else{mon = ""+month;}return year+"-"+mon+"-"+day;}}package com.longtu.rpt.app.view.rptview.multisheet;import java.awt.BorderLayout;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.Point;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.BorderFactory;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JDialog;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JSpinner;import javax.swing.JTable;import javax.swing.JTextField;import javax.swing.SpinnerListModel;import javax.swing.SpinnerModel;import javax.swing.SwingUtilities;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;import javax.swing.table.DefaultTableModel;import com.longtu.rpt.app.Main;public class DateChoiceControl extends JPanel{private static final long serialVersionUID = 287167130044293034L;public JTextField text;private JButton btn;private JButton btnLeft;private JButton btnRight;private JButton today;private JButton clear;private Object[] rowData = new Object[7];private JComboBox cmbMonth;private JSpinner spinYear;private JPanel content;private JPanel toolbar;private JPanel center;private JPanel bottom;private JTable table;private JDialog dialog;private Container owner;private int years;private int month;private int width = 220; //日期控件的宽度private int height = 200; //日期控件的高度private DefaultTableModel model = new DefaultTableModel() {private static final long serialVersionUID =-6721045359549509763L;@Overridepublic boolean isCellEditable(int row, int column) {return false;}};public DateChoiceControl(String name, int year,int mon){years = year;month = mon;BorderLayout b = new BorderLayout();this.setLayout(b);text = new JTextField();text.setPreferredSize(new Dimension(76,20));text.setEditable(false);this.add(text,b.WEST);btn = new JButton(null,newImageIcon(Main.class.getResource("/icons/dialog.png")));btn.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {if(JDialog.isDefaultLookAndFeelDecorated()){JDialog.setDefaultLookAndFeelDecorated(false);}Frame owner = (Frame) SwingUtilities.getWindowAncestor(DateChoiceControl.this);Rectangle r = text.getBounds();Point pOnScreen = text.getLocationOnScreen();Point result = new Point(pOnScreen.x, pOnScreen.y +r.height);Point powner = owner.getLocation();int offsetX = (pOnScreen.x + width)- (powner.x +owner.getWidth());int offsetY = (pOnScreen.y + r.height + height)- (powner.y +owner.getHeight());if (offsetX > 0) {result.x -= offsetX;}if (offsetY > 0) {result.y -= height + r.height;}dialog = new JDialog();dialog.setModal(false);dialog.setUndecorated(true);dialog.setResizable(true);dialog.setLocation(result);dialog.setSize(width, height);dialog.addWindowListener(new WindowAdapter() {//在任意的非日期选择区单击,则日期选择组件将变为非活动状态,自动释放资源。

java日历

java日历

Java日历一、开发语言:java二、开发环境:MyEclipse8.6三、项目名称:java日历控件四、程序运行截图:1.通过单击更改年份:2.通过单击更改月份3.通过单击更改日期4.通过键盘方向键更改日期5.右击将快捷第显示当天的日历6.windows日历展示:7.通过双击可以关闭日历8.该日历的实质是一个去掉了修饰的JFrame9.通过右上角很小的关闭按钮也可以关闭日历10.该日历应用于其它应用程序进行日期输入,日期修改五、程序源文件文件一:package net.cqwu.control;/*_*=====使用已有类Calendar======*_*/import java.text.DateFormatSymbols;import java.util.*;/*** @version 1.4 2007-04-07* @author Cay Horstmann*/public class StandardCalendar{public static void main(String[] args) {GregorianCalendar d = new GregorianCalendar();StandardCalendar s= new StandardCalendar(d.get(Calendar.YEAR), d.get(Calendar.MONTH) - 1, d.get(Calendar.DAY_OF_MONTH));System.out.print(s.getCalendarString());String [][] b = s.getCalendarNumber2D(s.calendarString);int[][] a = s.getMinIndexOutOfMonth(b);for (int[] t: a){for (int p : t){System.out.print(p + " ");}}}public StandardCalendar(int ye, int mo, int da) {super();this.ye = ye;this.mo = mo;this.da = da;}public String getCalendarString(){calendarString = "";// construct d as current dateGregorianCalendar d = new GregorianCalendar(ye, mo, da);int today = d.get(Calendar.DAY_OF_MONTH);System.out.println("今天" + today + "号");int month = d.get(Calendar.MONTH);System.out.println("今天" + (month + 1) + "月");//set d to start date of the monthd.set(Calendar.DAY_OF_MONTH,1);// DAY_OF_WEEK表示一个周中的第几天int weekday = d.get(Calendar.DAY_OF_WEEK);System.out.println("日历当天是一周中的第"+weekday + "天");//get first day of week (Sunday in the U.S.)int firstDayOfWeek = d.getFirstDayOfWeek();// 如果一个月的第一天就是一个周的第一天,就输出上一个月的倒数七天String preMonthString = "";while (weekday == firstDayOfWeek){d.add(Calendar.DAY_OF_MONTH,-1);String temp = "" +d.get(Calendar.DAY_OF_MONTH);preMonthString = temp + " " + preMonthString;System.out.println(temp);weekday = d.get(Calendar.DAY_OF_WEEK);// GregorianCalendar temp1 = new GregorianCalendar(d.get(Calendar.YEAR), d.get(Calendar.MONTH)-1, 1);// do// {// preMonthDays++;// temp1.add(Calendar.DAY_OF_MONTH, 1);// }while(temp1.get(Calendar.MONTH)==month-1);// System.out.println("前一个月有:" + preMonthDays + "天");}//determine the required indentation for the first lineint indent = 0;while(weekday != firstDayOfWeek){indent ++;d.add(Calendar.DAY_OF_MONTH,-1);String temp = "" +d.get(Calendar.DAY_OF_MONTH);preMonthString = temp + " " + preMonthString;System.out.println(temp);weekday = d.get(Calendar.DAY_OF_WEEK);}System.out.println(preMonthString);//print weekday namesString[] weekdayNames = new DateFormatSymbols().getShortWeekdays();do{System.out.printf("%4s",weekdayNames[weekday]);d.add(Calendar.DAY_OF_MONTH,1);weekday = d.get(Calendar.DAY_OF_WEEK);}while(weekday != firstDayOfWeek);System.out.println();// for(int i = 1 ;i <= indent;i++)// {// System.out.print(" ");// }if (preMonthString.length()==21){System.out.print(preMonthString + "\n");calendarString += preMonthString + "\n";}else{System.out.print(preMonthString);calendarString += preMonthString;}d.set(Calendar.DAY_OF_MONTH,1);do{//print dayint day = d.get(Calendar.DAY_OF_MONTH);System.out.printf("%2d",day);if (day < 10){calendarString += " " + day;}else{calendarString += day;}// mark current day with *if(day == today){System.out.print("*");calendarString += "*";}else{System.out.print(" ");calendarString += " ";}//advance d to the next dayd.add(Calendar.DAY_OF_MONTH,1);weekday = d.get(Calendar.DAY_OF_WEEK);//start a new line at the start of the week if(weekday == firstDayOfWeek){System.out.println();calendarString += "\n";}}while(d.get(Calendar.MONTH) == month);//the loop exits when d is day 1 of the next month// 填充日历中的尾部do{//print dayint day = d.get(Calendar.DAY_OF_MONTH);System.out.printf("%2d",day);if (day < 10){calendarString += " " + day;}else{calendarString += day;}// mark current day with *if(day == today){System.out.print("*");calendarString += "*";}else{System.out.print(" ");calendarString += " ";}//advance d to the next dayd.add(Calendar.DAY_OF_MONTH,1);weekday = d.get(Calendar.DAY_OF_WEEK);//start a new line at the start of the weekif(weekday == firstDayOfWeek){System.out.println();calendarString += "\n";}}while(calendarString.length()<=131);// System.out.println("月份" + d.get(Calendar.MONTH));//print final end of line if necessary// if(weekday != firstDayOfWeek)// System.out.println();// System.out.println(calendarString);return calendarString;}// 获得一维日历字符串数组public String[] getCalendarNumber(String calendarString){String[] tempArray = calendarString.split("\n");String standardString = "";String[] standardStringArray = new String[42];for (int i = 0; i < tempArray.length; i ++){standardString += tempArray[i];}// System.out.println(standardString);int standardStringLength = standardString.length();for (int i = 0, j = 1, k =0 ; i < standardStringLength - 2 && j < standardStringLength - 1 && k < 49; i += 3, j += 3, k ++) {standardStringArray[k] = (standardString.charAt(i)==' '?"":standardString.charAt(i)) +""+ standardString.charAt(j);}// for (String temp : standardStringArray)// {// System.out.print(temp + " ");// }return standardStringArray;}// 获得二维日历字符串数组public String[][] getCalendarNumber2D(String calendarString){String[][] standardStringArray2D = new String[6][7];String[] temp = this.getCalendarNumber(this.calendarString);for (int i = 0; i < temp.length; i++) {standardStringArray2D[i/7][i%7] = temp[i];}System.out.println("输出二维数组");for (String [] temp1 : standardStringArray2D){for (String temp2 : temp1){System.out.print(temp2 + " ");}System.out.println();}return standardStringArray2D;}// 该方法用于获得本日历的两个1的索引public int[][] getMinIndexOutOfMonth(String[][] temp){int[][] index = {{0,0}, {0, 0}};for (int i = 0; i < 6; i++) {for (int j = 0; j < 7; j++) {if (Integer.parseInt(temp[i][j]) == 1 && i < 2){index[0][0] = i;index[0][1] = j;}if (Integer.parseInt(temp[i][j]) == 1 && i > 2){index[1][0] = i;index[1][1] = j;}}}return index;}public int getYe() {return ye;}public void setYe(int ye) {this.ye = ye;}public int getMo() {return mo;}public void setMo(int mo) {this.mo = mo;}public int getDa() {return da;}public void setDa(int da) {this.da = da;}private String calendarString = null;private int ye ;private int mo;private int da;};文件二:package net.cqwu.control;import java.awt.Toolkit;/*** 定义一个接口,获得显示器的大小* @version 2011-04-26* @author yelin*/public interface ScreenSize{public static final int DEFAULT_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;public static final int DEFAULT_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;};文件三:package net.cqwu.model;import java.awt.Color;import java.awt.Cursor;import java.awt.EventQueue;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.MouseWheelEvent;import java.awt.event.MouseWheelListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.awt.font.FontRenderContext;import java.awt.font.LineMetrics;import java.awt.geom.Rectangle2D;import java.util.Calendar;import java.util.GregorianCalendar;import javax.swing.JFrame;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JPopupMenu;import javax.swing.event.MouseInputListener;import net.cqwu.control.ScreenSize;import net.cqwu.control.StandardCalendar;/*** 设计一个日历控件,可以在任何地方使用.* 使用说明:若作为控件使用请转至691行作用,在MainCalendar构造时注册* 你自己的类,进行对象之间的通讯,可以在691行处获取日历。

使用Java创建简单的日历应用程序

使用Java创建简单的日历应用程序

使用Java创建简单的日历应用程序-一个实战教程日历应用程序是一个有用的工具,它允许用户记录和管理事件、约会和提醒。

在这个实战博客中,我们将创建一个Java日历应用程序,演示如何使用Java编程语言和图形用户界面(GUI)库来实现事件管理和日期选择功能。

以下是本实战博客的主要内容:项目概述准备工作创建Java项目设计GUI界面实现日历视图添加事件管理功能总结让我们开始吧!1. 项目概述在本项目中,我们将创建一个简单的Java日历应用程序,它包括以下主要功能:显示日历界面,允许用户选择日期。

在日历中标记已经安排的事件和约会。

允许用户添加、编辑和删除事件。

提供事件的日期和时间提醒功能。

我们将使用Java编程语言和Swing GUI库来构建这个日历应用程序。

2. 准备工作在开始之前,确保您的开发环境已设置好。

我们将使用Java编程语言和Swing库来构建日历应用程序,不需要额外的工具或库。

3. 创建Java项目首先,创建一个新的Java项目,您可以使用任何Java集成开发环境(IDE)来完成此操作。

在项目中,我们将创建Java类来实现日历应用程序。

4. 设计GUI界面我们将创建一个简单的Swing GUI界面,用于显示日历界面和事件列表。

创建一个Java类,例如CalendarApp,并在其中创建GUI界面。

javaCopy codeimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Calendar;import java.util.Date;public class CalendarApp {private JFrame frame;private JPanel calendarPanel;private JPanel eventPanel;private JTextArea eventList;private JButton addButton;private JButton editButton;private JButton deleteButton;public CalendarApp() {frame = new JFrame("日历应用程序");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(800, 600);frame.setLayout(new BorderLayout());calendarPanel = new JPanel(new BorderLayout());eventPanel = new JPanel(new BorderLayout());eventList = new JTextArea();eventList.setEditable(false);JScrollPane eventScrollPane = new JScrollPane(eventList);addButton = new JButton("添加事件");editButton = new JButton("编辑事件");deleteButton = new JButton("删除事件");eventPanel.add(eventScrollPane, BorderLayout.CENTER);eventPanel.add(addButton, BorderLayout.NORTH);eventPanel.add(editButton, BorderLayout.WEST);eventPanel.add(deleteButton, BorderLayout.EAST);frame.add(calendarPanel, BorderLayout.WEST);frame.add(eventPanel, BorderLayout.CENTER);addButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {addEvent();}});editButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {editEvent();}});deleteButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {deleteEvent();}});frame.setVisible(true);}public static void main(String[] args) {SwingUtilities.invokeLater(() -> new CalendarApp());}private void addEvent() {// 实现添加事件的代码,略...}private void editEvent() {// 实现编辑事件的代码,略...}private void deleteEvent() {// 实现删除事件的代码,略...}}在上述代码中,我们创建了一个CalendarApp类,包括一个Swing窗口、日历界面和事件列表。

万年历Java窗体算法

万年历Java窗体算法

import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;public class text10 extends Frame {public static void main(String[] args) {new text10().aFrame();System.out.println( cal.get(Calendar.MONTH) );System.out.println( cal.get(Calendar.DATE) );System.out.println( cal.get(Calendar.DAY_OF_MONTH) );System.out.println( cal.get(Calendar.WEEK_OF_YEAR) );}private final String[] week = { "日", "一", "二", "三", "四", "五", "六" };private JLabel[] label_week = new JLabel[7];private JLabel[] label_day = new JLabel[42];public static Calendar cal=Calendar.getInstance();String str1 = "↓";private Button b1 = new Button(str1);String str2 = "↑";private Button b2 = new Button(str2);String str3 = "↓";private Button b3 = new Button(str3);String str4 = "↑";private Button b4 = new Button(str4);String str5 = "显示当月";private Button b5 = new Button(str5);String lstr1 = "年";private JLabel l1 = new JLabel(lstr1);String lstr2 = "月";private JLabel l2 = new JLabel(lstr2);static JLabel l3 = new JLabel();String tstr1=cal.get(Calendar.YEAR)+"";JTextField t1 = new JTextField(tstr1,4);String tstr2=cal.get(Calendar.MONTH)+1+"";JTextField t2 = new JTextField(tstr2,2);public void aFrame() {setLocation(500, 100);this.setSize(700, 500);this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);}});JPanel panel_day = new JPanel();panel_day.setLayout(new GridLayout(7, 7, 3, 3));for (int i = 0; i < 7; i++) {label_week[i] = new JLabel(" ");label_week[i].setText(week[i]);label_week[i].setForeground(Color.black);panel_day.add(label_week[i]);}label_week[0].setForeground(Color.red);label_week[6].setForeground(Color.red);for (int i = 0; i < 42; i++) {label_day[i] = new JLabel(" ");panel_day.add(label_day[i]);}this.paintDay();JPanel panel_ym = new JPanel();t1.addKeyListener(new KeyMonitor());t2.addKeyListener(new Key1Monitor());t1.setHorizontalAlignment(t1.LEFT);t2.setHorizontalAlignment(t2.LEFT);b1.addActionListener(new b1action());b2.addActionListener(new b2action());b3.addActionListener(new b3action());b4.addActionListener(new b4action());b5.addActionListener(new b5action());panel_ym.add(b1);panel_ym.add(t1);panel_ym.add(l1);panel_ym.add(b2);panel_ym.add(b3);panel_ym.add(t2);panel_ym.add(l2);panel_ym.add(b4);panel_ym.add(b5);JPanel panel_main = new JPanel();panel_main.setLayout(new BorderLayout());panel_main.add(panel_day, BorderLayout.SOUTH);panel_main.add(panel_ym, BorderLayout.NORTH);this.add(panel_main);this.setResizable(false);this.setVisible(true);pack();}private Date now_date = new Date();private String year_int = null;private int month_int;private void paintDay() {year_int=t1.getText().toString();month_int=Integer.parseInt(t2.getText());int year_sel = Integer.parseInt(year_int) - 1900;Date firstDay = new Date(year_sel, month_int-1, 1);GregorianCalendar cal = new GregorianCalendar();cal.setTime(firstDay);int days = 0;int day_week = 0;if (month_int == 1 || month_int == 3|| month_int == 5|| month_int == 7 || month_int == 8 || month_int == 10|| month_int == 12) {days = 31;} else if (month_int == 4 || month_int == 6 || month_int == 9|| month_int == 11) {days = 30;} else {if (cal.isLeapYear(year_sel)) {days = 29;} else {days = 28;}}day_week = firstDay.getDay();int count = 1;for (int i = day_week; i < day_week + days; count++, i++) { if (i % 7 == 0 || i == 6 || i == 13 || i == 20 || i == 27|| i == 34 || i == 41) {if (i == day_week + now_date.getDate() - 1) {label_day[i].setForeground(Color.blue);label_day[i].setText(count + "");} else {label_day[i].setForeground(Color.red);label_day[i].setText(count + "");}} else {if (i == day_week + now_date.getDate() - 1) {label_day[i].setForeground(Color.blue);label_day[i].setText(count + "");} else {label_day[i].setForeground(Color.black);label_day[i].setText(count + "");}}}}private class KeyMonitor extends KeyAdapter {public void keyTyped(KeyEvent event) {if (t1.getText().length() > 3) {event.consume();}}public void keyReleased(KeyEvent e) {t1.setText(t1.getText().replaceAll("\\D", ""));}public void keyPressed(KeyEvent e) {}}private class Key1Monitor extends KeyAdapter { public void keyTyped(KeyEvent event) {if (t2.getText().length() > 1) {event.consume();}}public void keyReleased(KeyEvent e) {t2.setText(t2.getText().replaceAll("\\D", ""));}public void keyPressed(KeyEvent e) {}}private class b5action implements ActionListener{ public void actionPerformed(ActionEvent e) { for(int i=0;i<42;i++){label_day[i].setText(" ");}paintDay();}}private class b4action implements ActionListener{ public void actionPerformed(ActionEvent e){String s="";int n=Integer.parseInt(t2.getText());n=n+1;if(n>=13){n=1;}s=s+n;t2.setText(s);}}private class b3action implements ActionListener{ public void actionPerformed(ActionEvent e){String s="";int n=Integer.parseInt(t2.getText());n=n-1;if(n<1){n=12;}s=s+n;t2.setText(s);}}private class b2action implements ActionListener{public void actionPerformed(ActionEvent e){String s="";int n=Integer.parseInt(t1.getText());n=n+1;s=s+n;t1.setText(s);}}private class b1action implements ActionListener{public void actionPerformed(ActionEvent e){String s="";int n=Integer.parseInt(t1.getText());n=n-1;if(n<=1582){n=1582;}s=s+n;t1.setText(s);}}}。

日历控件示例Java代码

日历控件示例Java代码

日历控件示例Java代码日历空间示例使用方法:将其代码复制粘贴进Eclipse或者Myeclipse中,再导入datepicker.jar 包即可,具体使用步骤请参考本人上传的JavaSwing日历控件.doc文件。

package com.shyhao.software;import java.awt.Color;import java.awt.Dimension; import java.awt.Font;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import java.util.Locale; import javax.swing.JButton;import javax.swing.JFrame; import javax.swing.JLabel; importjavax.swing.JTextField; import javax.swing.UIManager;import ponents.ui.DatePicker;public class DatePickerWin extends JFrame implementsActionListener{ //************************************ private DatePicker datepick; private static final String DefaultFormat = \ private Date date=new Date(); private Font font=new Font(\ private Dimension dimension=new Dimension(177,24); private int[] hilightDays={1,3,5,7}; private int[] disabledDays={4,6,5,9}; //************************************ private JTextField txtField; private JTextField valueField; private JButton getButton; /** * Create the frame */ public DatePickerWin() { super();setTitle(\ getContentPane().setBackground(Color.WHITE);getContentPane().setLayout(null); setLocationRelativeTo(null);//此句可保证Component位居屏幕中间 setSize(487, 315);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//*********************************************************************//datepick = new DatePicker(); 全部设为默认值 //datepick = newDatePicker(date,null,null,null);//自定义参数值 //datepick = newDatePicker(date,DefaultFormat,null,dimension);//自定义参数值 //datepick = new DatePicker(null,DefaultFormat,null,dimension);//自定义参数值 //各参数含义如下 //参数1 设置该控件的初始值(可选) //参数2 设置日期的格式(可选) //参数3 设置该控件的字体(可选) //参数3 设置该控件的大小(可选) //该控件继承自JComponent ,它继承了Jcomponent的属性 datepick = new DatePicker(date,DefaultFormat,font,dimension);//自定义参数值//datepick.setLocation(137, 83); datepick.setBounds(137, 83, 177, 24); datepick.setHightlightdays(hilightDays, Color.red);//设置一个月份中需要高亮显示的日子 datepick.setDisableddays(disabledDays);//设置一个月份中不需要的日子,呈灰色显示 datepick.setLocale(Locale.CHINA);//设置国家datepick.setTimePanleVisible(true);//设置时钟面板可见getContentPane().add(datepick);//********************************************************************************* valueField = new JTextField(); valueField.setBounds(137, 138, 177, 21); getContentPane().add(valueField); txtField = new JTextField(); txtField.setBounds(137, 187, 177, 21); getContentPane().add(txtField); getButton = new JButton(); getButton.addActionListener(this);getButton.setText(\ getButton.setBounds(10, 163, 64, 23); getContentPane().add(getButton); final JLabel valueLabel = new JLabel(); valueLabel.setText(\ valueLabel.setBounds(88, 141, 43, 15);getContentPane().add(valueLabel); final JLabel txtLabel = new JLabel(); txtLabel.setText(\ txtLabel.setBounds(96, 190, 35, 15);getContentPane().add(txtLabel); // } public voidactionPerformed(ActionEvent e) { //*************************************** Date date=(Date)datepick.getValue(); String txt=datepick.getText(); valueField.setText(date.toString()); txtField.setText(txt);//************************************** } /** * Launch the application * * @param args */ public static void main(String args[]) { try { UIManager.setLookAndFeel(\Windows外观 } catch (Exception e) {}}}DatePickerWin frame = new DatePickerWin(); frame.setVisible(true);感谢您的阅读,祝您生活愉快。

java 弹窗方法

java 弹窗方法

java 弹窗方法在Java中,要创建一个弹窗,可以使用Swing库中的JOptionPane类。

JOptionPane类提供了一系列静态方法,可以方便地创建各种类型的弹窗,如消息框、确认框、输入框等。

下面是几种常见的弹窗方法:1. 消息框:javaJOptionPane.showMessageDialog(null, "这是一个消息框");这个方法会创建一个消息框,其中第一个参数是父组件,null表示没有父组件,第二个参数是要显示的消息。

2. 确认框:javaint result = JOptionPane.showConfirmDialog(null, "你确定要删除吗?");if (result == JOptionPane.YES_OPTION) {// 用户点击了确定按钮// 执行删除操作} else if (result == JOptionPane.NO_OPTION) {// 用户点击了取消按钮// 执行取消操作}这个方法会创建一个确认框,其中第一个参数是父组件,null表示没有父组件,第二个参数是要显示的消息。

方法的返回值是用户点击的按钮,可以通过判断返回值来执行相应的操作。

3. 输入框:javaString input = JOptionPane.showInputDialog(null, "请输入你的姓名:");if (input != null) {// 用户输入了姓名// 执行相应的操作}这个方法会创建一个输入框,其中第一个参数是父组件,null表示没有父组件,第二个参数是要显示的消息。

方法的返回值是用户输入的字符串,可以通过判断返回值是否为null来判断用户是否输入了内容。

以上是几种常见的弹窗方法,你可以根据需要选择适合的方法来创建弹窗。

Javawebjsp页面实现日历的显示(WdatePicker控件)

Javawebjsp页面实现日历的显示(WdatePicker控件)

Javawebjsp页⾯实现⽇历的显⽰(WdatePicker控件)<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><script language="javascript" type="text/javascript"src="js/My97DatePicker/WdatePicker.js"></script><script type="text/javascript"><% java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd");java.util.Date currentTime = new java.util.Date();//得到当前系统时间String str_date = formatter.format(currentTime); //将⽇期时间格式化%></script><div id="div1"></div><script>WdatePicker({eCont:'div1',onpicked:function(dp){alert()}})</script></head><body></body></html>。

java 弹窗方法 -回复

java 弹窗方法 -回复

java 弹窗方法-回复Java弹窗方法Java是一种高级的编程语言,常用于开发各种跨平台的应用程序。

在Java 中,弹窗是一种常见的用户界面元素,用于向用户显示消息、警告或者询问用户的输入。

本文将介绍Java中的弹窗方法,并逐步解释如何使用它们。

第一步:导入必要的类库在使用Java中的弹窗方法之前,我们需要导入相关的类库。

Java提供了javax.swing包来实现弹窗功能。

我们可以使用`import`语句引入这个包,以便在我们的代码中使用相关的类和方法。

在代码的开头添加以下语句:javaimport javax.swing.JOptionPane;第二步:显示简单的消息弹窗使用Java中的弹窗方法,我们可以很方便地向用户显示消息。

其中最简单的方法就是使用`JOptionPane.showMessageDialog()`方法。

该方法接受三个参数:弹窗的父组件、要显示的消息和弹窗的标题。

以下是一个简单的示例:javaJOptionPane.showMessageDialog(null, "Hello, World!", "Welcome", RMATION_MESSAGE);在这个示例中,我们使用`null`作为弹窗的父组件,这意味着弹窗将会出现在屏幕的中央。

我们要显示的消息是"Hello, World!",弹窗的标题是"Welcome"。

`RMATION_MESSAGE`参数表示这是一个信息类型的消息弹窗。

第三步:显示带有选项的消息弹窗除了显示简单的消息,Java的弹窗方法还可以显示具有选项的消息弹窗。

我们可以使用`JOptionPane.showOptionDialog()`方法来实现这个功能。

该方法接受六个参数:弹窗的父组件、要显示的消息、弹窗的标题、选项按钮的类型、弹窗的图标类型以及默认选项按钮。

以下是一个显示带有选项的消息弹窗的示例:javaString[] options = {"Yes", "No", "Cancel"};int response = JOptionPane.showOptionDialog(null, "Do you want to save the changes?", "Save",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);if (response == JOptionPane.YES_OPTION) {用户选择了"Yes"按钮} else if (response == JOptionPane.NO_OPTION) {用户选择了"No"按钮} else if (response == JOptionPane.CANCEL_OPTION) {用户选择了"Cancel"按钮} else if (response == JOptionPane.CLOSED_OPTION) {用户关闭了弹窗}在这个示例中,我们定义了一个选项按钮的数组,其中包含"Yes"、"No"和"Cancel"三个选项。

Java Swing单击文本框弹出日历组件

Java Swing单击文本框弹出日历组件

Java Swing单击文本框弹出日历组件2011-04-07 16:12package com.niit.swing2;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Font;import java.awt.Frame;import java.awt.GridLayout;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JFormattedTextField;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JSpinner;import javax.swing.SpinnerNumberModel;import javax.swing.SwingConstants;import javax.swing.SwingUtilities;import javax.swing.border.LineBorder;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;public class DateChooser extends JPanel implements ActionListener, ChangeListener {/****/private static final long serialVersionUID = 1L;int startYear = 1980; //默认【最小】显示年份int lastYear = 2050; //默认【最大】显示年份int width = 270; //界面宽度int height = 200; //界面高度Color backGroundColor = Color.gray; //底色//月历表格配色----------------//Color palletTableColor = Color.white; //日历表底色Color todayBackColor = Color.orange; //今天背景色Color weekFontColor = Color.blue; //星期文字色Color dateFontColor = Color.black; //日期文字色Color weekendFontColor = Color.red; //周末文字色//控制条配色------------------//Color controlLineColor = Color.pink; //控制条底色Color controlTextColor = Color.white; //控制条标签文字色Color rbFontColor = Color.white; //RoundBox文字色Color rbBorderColor = Color.red; //RoundBox边框色Color rbButtonColor = Color.pink; //RoundBox按钮色Color rbBtFontColor = Color.red; //RoundBox按钮文字色JDialog dialog; //用于显示日期选择控件JSpinner yearSpin; //调节年份的JSpinnerJSpinner monthSpin; //调节月份JSpinner hourSpin; //调节小时JSpinner minuteSpin;//调节分钟JButton[][] daysButton = new JButton[6][7];//用于显示当前月份每一天所对应的星期的按钮数组JFormattedTextField jFormattedTextField;//显示当前选择日期的有格式输入框Calendar c = getCalendar();Calendar cal = Calendar.getInstance();int currentDay=cal.get(Calendar.DAY_OF_MONTH);DateChooser(JFormattedTextField jftf) {jFormattedTextField = jftf;//设置布局及边框setLayout(new BorderLayout());setBorder(new LineBorder(backGroundColor, 2));setBackground(backGroundColor);//初始化及添加子面板JPanel topYearAndMonth = createYearAndMonthPanal();add(topYearAndMonth, BorderLayout.NORTH);JPanel centerWeekAndDay = createWeekAndDayPanal();add(centerWeekAndDay, BorderLayout.CENTER);}/**** 功能描述:用于创建年份及月份显示面板* @return 用于创建年份及月份显示面板JPanel对象*/private JPanel createYearAndMonthPanal() {int currentYear = c.get(Calendar.YEAR);int currentMonth = c.get(Calendar.MONTH) + 1;int currentHour = c.get(Calendar.HOUR_OF_DAY);int currentMinute = c.get(Calendar.MINUTE);JPanel result = new JPanel();result.setLayout(new FlowLayout());result.setBackground(controlLineColor);yearSpin = new JSpinner(new SpinnerNumberModel(currentYear, startYear, lastYear, 1));yearSpin.setPreferredSize(new Dimension(48, 20));yearSpin.setName("Year");yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));yearSpin.addChangeListener(this);result.add(yearSpin);JLabel yearLabel = new JLabel("年");yearLabel.setForeground(controlTextColor);result.add(yearLabel);monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1, 12, 1)); monthSpin.setPreferredSize(new Dimension(35, 20));monthSpin.setName("Month");monthSpin.addChangeListener(this);result.add(monthSpin);JLabel monthLabel = new JLabel("月");monthLabel.setForeground(controlTextColor);result.add(monthLabel);hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23, 1)); hourSpin.setPreferredSize(new Dimension(35, 20));hourSpin.setName("Hour");hourSpin.addChangeListener(this);result.add(hourSpin);JLabel hourLabel = new JLabel("时");hourLabel.setForeground(controlTextColor);result.add(hourLabel);minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59,1));minuteSpin.setPreferredSize(new Dimension(35, 20));minuteSpin.setName("Minute");minuteSpin.addChangeListener(this);result.add(minuteSpin);JLabel minuteLabel = new JLabel("分");minuteLabel.setForeground(controlTextColor);result.add(minuteLabel);return result;}/**** 功能描述:用于创建当前月份中每一天按对应星期排列所在面板* @return*/private JPanel createWeekAndDayPanal() {String colname[] = { "日", "一", "二", "三", "四", "五", "六" };JPanel result = new JPanel();//设置固定字体,以免调用环境改变影响界面美观result.setFont(new Font("宋体", Font.PLAIN, 12));result.setLayout(new GridLayout(7, 7));result.setBackground(Color.white);JLabel cell; //显示星期for (int i = 0; i < 7; i++) {cell = new JLabel(colname[i]);cell.setHorizontalAlignment(JLabel.CENTER);if (i == 0 || i == 6)cell.setForeground(weekendFontColor);elsecell.setForeground(weekFontColor);result.add(cell);}int actionCommandId = 0;for (int i = 0; i < 6; i++)for (int j = 0; j < 7; j++) {JButton numberButton = new JButton();numberButton.setBorder(null);numberButton.setHorizontalAlignment(SwingConstants.CENTER);numberButton.setActionCommand(String.valueOf(actionCommandId));numberButton.addActionListener(this);numberButton.setBackground(palletTableColor);numberButton.setForeground(dateFontColor);if (j == 0 || j == 6)numberButton.setForeground(weekendFontColor);elsenumberButton.setForeground(dateFontColor);daysButton[i][j] = numberButton;numberButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) {if (e.getClickCount() == 2) { //鼠标双击再次时closeAndSetDate();}}});result.add(numberButton);actionCommandId++;}return result;}private JDialog createDialog(Frame owner) {JDialog result = new JDialog(owner, "日期时间选择", true);result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);result.getContentPane().add(this, BorderLayout.CENTER);result.pack();result.setSize(width, height);return result;}public void showDateChooser(Point position) {Object tmpobj=SwingUtilities.getWindowAncestor(jFormattedTextField);if(tmpobj.getClass().isInstance(new JDialog())||tmpobj.getClass().getSuperclass().isInstance(new JDialog())) {JDialog ownerdialog = (JDialog) SwingUtilities.getWindowAncestor(jFormattedTextField);Frame owner = (Frame) SwingUtilities.getWindowAncestor(ownerdialog);if (dialog == null || dialog.getOwner() != owner) {dialog = createDialog(owner);}dialog.setLocation(getAppropriateLocation(owner, position));}else if(tmpobj.getClass().isInstance(new JFrame())||tmpobj.getClass().getSuperclass().isInstance(new JFrame())) {JFrame ownerFrame = (JFrame) SwingUtilities.getWindowAncestor(jFormattedTextField);if (dialog == null || dialog.getOwner() != ownerFrame) {dialog = createDialog(ownerFrame);}dialog.setLocation(getAppropriateLocation(ownerFrame, position));}flushWeekAndDay();dialog.setVisible(true);}Point getAppropriateLocation(Frame owner, Point position) { Point result = new Point(position);Point p = owner.getLocation();int offsetX = (position.x + width) - (p.x + owner.getWidth());int offsetY = (position.y + height) - (p.y + owner.getHeight());if (offsetX > 0) {result.x -= offsetX;}if (offsetY > 0) {result.y -= offsetY;}return result;}public void closeAndSetDate() {setDate(c.getTime());dialog.dispose();}private Calendar getCalendar() {Calendar result = Calendar.getInstance();result.setTime(getDate());return result;}private int getSelectedYear() {return ((Integer) yearSpin.getValue()).intValue(); }private int getSelectedMonth() {return ((Integer) monthSpin.getValue()).intValue(); }private int getSelectedHour() {return ((Integer) hourSpin.getValue()).intValue();}private int getSelectedMinute() {return ((Integer) minuteSpin.getValue()).intValue();}private void dayColorUpdate(boolean isOldDay) {int day = c.get(Calendar.DAY_OF_MONTH);// System.out.println(day+"-----day-----");c.set(Calendar.DAY_OF_MONTH, currentDay);// System.out.println("当前日期day:"+c.get(Calendar.DATE));int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);int i = actionCommandId / 7;int j = actionCommandId % 7;if (isOldDay)daysButton[i][j].setForeground(dateFontColor);elsedaysButton[i][j].setForeground(todayBackColor);}private void flushWeekAndDay() {c.set(Calendar.DAY_OF_MONTH, currentDay);int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);// System.out.println("某月日期值范围:"+dayNo+"----"+maxDayNo);for (int i = 0; i < 6; i++) {for (int j = 0; j < 7; j++) {String s = "";if (dayNo >= 1 && dayNo <= maxDayNo)s = String.valueOf(dayNo);daysButton[i][j].setText(s);dayNo++;}}dayColorUpdate(false);}public void stateChanged(ChangeEvent e) {JSpinner source = (JSpinner) e.getSource();if (source.getName().equals("Minute")) {c.set(Calendar.MINUTE, getSelectedMinute());return;}if (source.getName().equals("Hour")) {c.set(Calendar.HOUR_OF_DAY, getSelectedHour());return;}dayColorUpdate(true);if (source.getName().equals("Year")) {c.set(Calendar.YEAR, getSelectedYear());}if (source.getName().equals("Month")) {c.set(Calendar.MONTH, getSelectedMonth() - 1);}flushWeekAndDay();}public void actionPerformed(ActionEvent e) {JButton source = (JButton) e.getSource();if (source.getText().length() == 0)return;dayColorUpdate(true);source.setForeground(todayBackColor);int newDay = Integer.parseInt(source.getText());c.set(Calendar.DAY_OF_MONTH, newDay);}public void setDate(Date date) {jFormattedTextField.setText(getDefaultDateFormat().format(date));}public Date getDate() {try {String dateString = jFormattedTextField.getText();// System.out.println(dateString+"---------");return getDefaultDateFormat().parse(dateString);} catch (ParseException e) {return getNowDate();} catch (Exception ee) {return getNowDate();}}private static Date getNowDate() {return Calendar.getInstance().getTime();private static SimpleDateFormat getDefaultDateFormat() {return new SimpleDateFormat("yyyy-MM-dd HH:mm");}}----------------------------------------------------------MyTest-----------------------------------------package com.niit.swing2;import java.awt.Point;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JFormattedTextField;import javax.swing.JFrame;import javax.swing.JLabel;public class MyTest {private JFrame jf;private JFormattedTextField tfDate;private JLabel lb;public static void main(String[] args) {new MyTest().init();public void init(){jf=new JFrame("日期组件");jf.setLayout(null);jf.setBounds(10, 10, 300, 200);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);lb=new JLabel("选择日期:");lb.setBounds(15, 60, 80, 30);initTfDate();//初始化文本框jf.add(tfDate);jf.add(lb);jf.setVisible(true);}/** initTfDate 初始化JFormattedTextField tfDate;*/public void initTfDate(){tfDate=new JFormattedTextField();tfDate.setBounds(100, 60, 120, 23);tfDate.addMouseListener(new MouseListener(){public void mouseClicked(MouseEvent mouseevent) { //添加文本框单击事件// TODO Auto-generated method stub//System.out.println("------MyTest-----");DateChooser mDateChooser=new DateChooser(tfDate);//设置DateChooser弹出位置Point p = tfDate.getLocationOnScreen();p.y = p.y + 30;mDateChooser.showDateChooser(p);tfDate.requestFocusInWindow();}public void mouseEntered(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mousePressed(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mouseReleased(MouseEvent mouseevent) {// TODO Auto-generated method stub}}); }}。

java实现点击按钮事件弹出子窗口

java实现点击按钮事件弹出子窗口

java实现点击按钮事件弹出⼦窗⼝本⽂实例为⼤家分享了java实现点击按钮事件弹出⼦窗⼝的具体代码,供⼤家参考,具体内容如下要求:1、在⽗窗⼝中添加⼀个按钮2、点击按钮弹出⼦窗⼝注意:这是JDK1.7版本在JDK1.7之前,JFrame是不能直接添加⼦窗⼝的,要先将JInternalFrame添加到JDesktopPane中,再将JDesktopPane添加到⽗窗⼝内,完成这个操作。

(⼀)建⽴⽗类JFramepackage com.java.view;import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JDesktopPane;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JMenuBar;public class Testfrm extends JFrame {/*** Launch the application.*/public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {Testfrm frame = new Testfrm();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/*** Create the frame.*/public Testfrm() {setTitle("\u7236\u7A97\u53E3");//标题setBounds(400, 300, 800, 600);//⽗窗⼝的坐标和⼤⼩getContentPane().setLayout(null);//⾃由布局JButton bt = new JButton("\u6309\u94AE");//按钮的变量名为btbt.setBounds(0, 0, 93, 23);//按钮的位置坐标和⼤⼩getContentPane().add(bt);//按钮添加到窗⼝中bt.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {Testinterfrm testinterfrm=new Testinterfrm();//新建⼦窗⼝对象testinterfrm.setVisible(true);//⼦窗⼝可见getContentPane().add(testinterfrm);//⼦窗⼝添加到⽗窗⼝中}});}}(⼆)建⽴⼦类JInternalFramepackage com.java.view;import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JDesktopPane;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JMenuBar;public class Testfrm extends JFrame {/*** Launch the application.*/public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {Testfrm frame = new Testfrm();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/*** Create the frame.*/public Testfrm() {setTitle("\u7236\u7A97\u53E3");//标题setBounds(400, 300, 800, 600);//⽗窗⼝的坐标和⼤⼩getContentPane().setLayout(null);//⾃由布局JButton bt = new JButton("\u6309\u94AE");//按钮的变量名为btbt.setBounds(0, 0, 93, 23);//按钮的位置坐标和⼤⼩getContentPane().add(bt);//按钮添加到窗⼝中bt.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {Testinterfrm testinterfrm=new Testinterfrm();//新建⼦窗⼝对象testinterfrm.setVisible(true);//⼦窗⼝可见getContentPane().add(testinterfrm);//⼦窗⼝添加到⽗窗⼝中}});}}运⾏结果:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java三种组件的使用方法

java三种组件的使用方法

Java中常用的三种组件分别是JButton、JTextField和JLabel,它们的使用方法如下:1. JButton组件JButton组件是Java GUI编程中常用的一个组件,它可以用来创建按钮。

使用JButton组件需要先创建一个Button对象,然后设置按钮的文本、点击事件等属性。

以下是一个示例代码:JButton button = new JButton("Click me");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked me!");}});在上面的代码中,我们首先创建了一个JButton对象,然后设置按钮的文本为"Click me",并添加了一个点击事件的监听器。

当用户点击按钮时,程序将弹出一个对话框,显示"You clicked me!"的消息。

2. JTextField组件JTextField组件是Java GUI编程中常用的一个文本输入框组件。

使用JTextField组件需要先创建一个TextField对象,然后设置文本框的属性,如文本内容、字体、颜色等。

以下是一个示例代码:JTextField textField = new JTextField("Enter some text here...");textField.setFont(new Font("Arial", Font.BOLD, 16));textField.setForeground(Color.blue);在上面的代码中,我们首先创建了一个JTextField对象,然后设置文本框的文本为"Enter some text here...",并设置字体、颜色等属性。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java Swing单击文本框弹出日历组件2011-04-07 16:12package com.niit.swing2;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Font;import java.awt.Frame;import java.awt.GridLayout;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JFormattedTextField;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JSpinner;import javax.swing.SpinnerNumberModel;import javax.swing.SwingConstants;import javax.swing.SwingUtilities;import javax.swing.border.LineBorder;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;public class DateChooser extends JPanel implements ActionListener, ChangeListener {/****/private static final long serialVersionUID = 1L;int startYear = 1980; //默认【最小】显示年份int lastYear = 2050; //默认【最大】显示年份int width = 270; //界面宽度int height = 200; //界面高度Color backGroundColor = Color.gray; //底色//月历表格配色----------------//Color palletTableColor = Color.white; //日历表底色Color todayBackColor = Color.orange; //今天背景色Color weekFontColor = Color.blue; //星期文字色Color dateFontColor = Color.black; //日期文字色Color weekendFontColor = Color.red; //周末文字色//控制条配色------------------//Color controlLineColor = Color.pink; //控制条底色Color controlTextColor = Color.white; //控制条标签文字色Color rbFontColor = Color.white; //RoundBox文字色Color rbBorderColor = Color.red; //RoundBox边框色Color rbButtonColor = Color.pink; //RoundBox按钮色Color rbBtFontColor = Color.red; //RoundBox按钮文字色JDialog dialog; //用于显示日期选择控件JSpinner yearSpin; //调节年份的JSpinnerJSpinner monthSpin; //调节月份JSpinner hourSpin; //调节小时JSpinner minuteSpin;//调节分钟JButton[][] daysButton = new JButton[6][7];//用于显示当前月份每一天所对应的星期的按钮数组JFormattedTextField jFormattedTextField;//显示当前选择日期的有格式输入框Calendar c = getCalendar();Calendar cal = Calendar.getInstance();int currentDay=cal.get(Calendar.DAY_OF_MONTH);DateChooser(JFormattedTextField jftf) {jFormattedTextField = jftf;//设置布局及边框setLayout(new BorderLayout());setBorder(new LineBorder(backGroundColor, 2));setBackground(backGroundColor);//初始化及添加子面板JPanel topYearAndMonth = createYearAndMonthPanal();add(topYearAndMonth, BorderLayout.NORTH);JPanel centerWeekAndDay = createWeekAndDayPanal();add(centerWeekAndDay, BorderLayout.CENTER);}/**** 功能描述:用于创建年份及月份显示面板* @return 用于创建年份及月份显示面板JPanel对象*/private JPanel createYearAndMonthPanal() {int currentYear = c.get(Calendar.YEAR);int currentMonth = c.get(Calendar.MONTH) + 1;int currentHour = c.get(Calendar.HOUR_OF_DAY);int currentMinute = c.get(Calendar.MINUTE);JPanel result = new JPanel();result.setLayout(new FlowLayout());result.setBackground(controlLineColor);yearSpin = new JSpinner(new SpinnerNumberModel(currentYear, startYear, lastYear, 1));yearSpin.setPreferredSize(new Dimension(48, 20));yearSpin.setName("Year");yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));yearSpin.addChangeListener(this);result.add(yearSpin);JLabel yearLabel = new JLabel("年");yearLabel.setForeground(controlTextColor);result.add(yearLabel);monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1, 12, 1)); monthSpin.setPreferredSize(new Dimension(35, 20));monthSpin.setName("Month");monthSpin.addChangeListener(this);result.add(monthSpin);JLabel monthLabel = new JLabel("月");monthLabel.setForeground(controlTextColor);result.add(monthLabel);hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23, 1)); hourSpin.setPreferredSize(new Dimension(35, 20));hourSpin.setName("Hour");hourSpin.addChangeListener(this);result.add(hourSpin);JLabel hourLabel = new JLabel("时");hourLabel.setForeground(controlTextColor);result.add(hourLabel);minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59,1));minuteSpin.setPreferredSize(new Dimension(35, 20));minuteSpin.setName("Minute");minuteSpin.addChangeListener(this);result.add(minuteSpin);JLabel minuteLabel = new JLabel("分");minuteLabel.setForeground(controlTextColor);result.add(minuteLabel);return result;}/**** 功能描述:用于创建当前月份中每一天按对应星期排列所在面板* @return*/private JPanel createWeekAndDayPanal() {String colname[] = { "日", "一", "二", "三", "四", "五", "六" };JPanel result = new JPanel();//设置固定字体,以免调用环境改变影响界面美观result.setFont(new Font("宋体", Font.PLAIN, 12));result.setLayout(new GridLayout(7, 7));result.setBackground(Color.white);JLabel cell; //显示星期for (int i = 0; i < 7; i++) {cell = new JLabel(colname[i]);cell.setHorizontalAlignment(JLabel.CENTER);if (i == 0 || i == 6)cell.setForeground(weekendFontColor);elsecell.setForeground(weekFontColor);result.add(cell);}int actionCommandId = 0;for (int i = 0; i < 6; i++)for (int j = 0; j < 7; j++) {JButton numberButton = new JButton();numberButton.setBorder(null);numberButton.setHorizontalAlignment(SwingConstants.CENTER);numberButton.setActionCommand(String.valueOf(actionCommandId));numberButton.addActionListener(this);numberButton.setBackground(palletTableColor);numberButton.setForeground(dateFontColor);if (j == 0 || j == 6)numberButton.setForeground(weekendFontColor);elsenumberButton.setForeground(dateFontColor);daysButton[i][j] = numberButton;numberButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) {if (e.getClickCount() == 2) { //鼠标双击再次时closeAndSetDate();}}});result.add(numberButton);actionCommandId++;}return result;}private JDialog createDialog(Frame owner) {JDialog result = new JDialog(owner, "日期时间选择", true);result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);result.getContentPane().add(this, BorderLayout.CENTER);result.pack();result.setSize(width, height);return result;}public void showDateChooser(Point position) {Object tmpobj=SwingUtilities.getWindowAncestor(jFormattedTextField);if(tmpobj.getClass().isInstance(new JDialog())||tmpobj.getClass().getSuperclass().isInstance(new JDialog())) {JDialog ownerdialog = (JDialog) SwingUtilities.getWindowAncestor(jFormattedTextField);Frame owner = (Frame) SwingUtilities.getWindowAncestor(ownerdialog);if (dialog == null || dialog.getOwner() != owner) {dialog = createDialog(owner);}dialog.setLocation(getAppropriateLocation(owner, position));}else if(tmpobj.getClass().isInstance(new JFrame())||tmpobj.getClass().getSuperclass().isInstance(new JFrame())) {JFrame ownerFrame = (JFrame) SwingUtilities.getWindowAncestor(jFormattedTextField);if (dialog == null || dialog.getOwner() != ownerFrame) {dialog = createDialog(ownerFrame);}dialog.setLocation(getAppropriateLocation(ownerFrame, position));}flushWeekAndDay();dialog.setVisible(true);}Point getAppropriateLocation(Frame owner, Point position) { Point result = new Point(position);Point p = owner.getLocation();int offsetX = (position.x + width) - (p.x + owner.getWidth());int offsetY = (position.y + height) - (p.y + owner.getHeight());if (offsetX > 0) {result.x -= offsetX;}if (offsetY > 0) {result.y -= offsetY;}return result;}public void closeAndSetDate() {setDate(c.getTime());dialog.dispose();}private Calendar getCalendar() {Calendar result = Calendar.getInstance();result.setTime(getDate());return result;}private int getSelectedYear() {return ((Integer) yearSpin.getValue()).intValue(); }private int getSelectedMonth() {return ((Integer) monthSpin.getValue()).intValue(); }private int getSelectedHour() {return ((Integer) hourSpin.getValue()).intValue();}private int getSelectedMinute() {return ((Integer) minuteSpin.getValue()).intValue();}private void dayColorUpdate(boolean isOldDay) {int day = c.get(Calendar.DAY_OF_MONTH);// System.out.println(day+"-----day-----");c.set(Calendar.DAY_OF_MONTH, currentDay);// System.out.println("当前日期day:"+c.get(Calendar.DATE));int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);int i = actionCommandId / 7;int j = actionCommandId % 7;if (isOldDay)daysButton[i][j].setForeground(dateFontColor);elsedaysButton[i][j].setForeground(todayBackColor);}private void flushWeekAndDay() {c.set(Calendar.DAY_OF_MONTH, currentDay);int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);// System.out.println("某月日期值范围:"+dayNo+"----"+maxDayNo);for (int i = 0; i < 6; i++) {for (int j = 0; j < 7; j++) {String s = "";if (dayNo >= 1 && dayNo <= maxDayNo)s = String.valueOf(dayNo);daysButton[i][j].setText(s);dayNo++;}}dayColorUpdate(false);}public void stateChanged(ChangeEvent e) {JSpinner source = (JSpinner) e.getSource();if (source.getName().equals("Minute")) {c.set(Calendar.MINUTE, getSelectedMinute());return;}if (source.getName().equals("Hour")) {c.set(Calendar.HOUR_OF_DAY, getSelectedHour());return;}dayColorUpdate(true);if (source.getName().equals("Year")) {c.set(Calendar.YEAR, getSelectedYear());}if (source.getName().equals("Month")) {c.set(Calendar.MONTH, getSelectedMonth() - 1);}flushWeekAndDay();}public void actionPerformed(ActionEvent e) {JButton source = (JButton) e.getSource();if (source.getText().length() == 0)return;dayColorUpdate(true);source.setForeground(todayBackColor);int newDay = Integer.parseInt(source.getText());c.set(Calendar.DAY_OF_MONTH, newDay);}public void setDate(Date date) {jFormattedTextField.setText(getDefaultDateFormat().format(date));}public Date getDate() {try {String dateString = jFormattedTextField.getText();// System.out.println(dateString+"---------");return getDefaultDateFormat().parse(dateString);} catch (ParseException e) {return getNowDate();} catch (Exception ee) {return getNowDate();}}private static Date getNowDate() {return Calendar.getInstance().getTime();private static SimpleDateFormat getDefaultDateFormat() {return new SimpleDateFormat("yyyy-MM-dd HH:mm");}}----------------------------------------------------------MyTest-----------------------------------------package com.niit.swing2;import java.awt.Point;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JFormattedTextField;import javax.swing.JFrame;import javax.swing.JLabel;public class MyTest {private JFrame jf;private JFormattedTextField tfDate;private JLabel lb;public static void main(String[] args) {new MyTest().init();public void init(){jf=new JFrame("日期组件");jf.setLayout(null);jf.setBounds(10, 10, 300, 200);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);lb=new JLabel("选择日期:");lb.setBounds(15, 60, 80, 30);initTfDate();//初始化文本框jf.add(tfDate);jf.add(lb);jf.setVisible(true);}/** initTfDate 初始化JFormattedTextField tfDate;*/public void initTfDate(){tfDate=new JFormattedTextField();tfDate.setBounds(100, 60, 120, 23);tfDate.addMouseListener(new MouseListener(){public void mouseClicked(MouseEvent mouseevent) { //添加文本框单击事件// TODO Auto-generated method stub//System.out.println("------MyTest-----");DateChooser mDateChooser=new DateChooser(tfDate);//设置DateChooser弹出位置Point p = tfDate.getLocationOnScreen();p.y = p.y + 30;mDateChooser.showDateChooser(p);tfDate.requestFocusInWindow();}public void mouseEntered(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mousePressed(MouseEvent mouseevent) {// TODO Auto-generated method stub}public void mouseReleased(MouseEvent mouseevent) {// TODO Auto-generated method stub}}); }}。

相关文档
最新文档