在 VB、C# 等其他语言中,在您希望用户输入日期的情况下,例如在文本框中,我们可以使日历在您单击后出现。所以用户可以点击相应的日期,该日期将被放入文本框中。
通过这种方式,我们可以摆脱由于日期格式不正确而导致的问题。我需要知道我们如何在java中实现这一点?
实际上,我需要将它与 JTable 结合起来。有一列需要输入日期。但用户可以输入各种格式的日期。所以我想去这样的事情。希望有一种方法可以轻松地做到这一点。
谁能告诉我如何做到这一点。任何帮助是极大的赞赏..
谢谢你。
我发现JXDatePicker是一个更好的解决方案。它提供了您需要的东西并且非常易于使用。
import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.JXDatePicker; public class DatePickerExample extends JPanel { public static void main(String[] args) { JFrame frame = new JFrame("JXPicker Example"); JPanel panel = new JPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(400, 400, 250, 100); JXDatePicker picker = new JXDatePicker(); picker.setDate(Calendar.getInstance().getTime()); picker.setFormats(new SimpleDateFormat("dd.MM.yyyy")); panel.add(picker); frame.getContentPane().add(panel); frame.setVisible(true); } }
我写了一个 DateTextField 组件。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
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 DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
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;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
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) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
LGoodDatePicker库包括一个(摆动)DatePicker组件,它允许用户从日历中选择日期。(默认情况下,用户也可以从键盘输入日期,但如果需要,可以禁用键盘输入)。DatePicker 具有自动数据验证功能,这意味着(除其他外)用户输入的任何日期都将始终转换为您想要的日期格式。
公平披露:我是主要开发人员。
由于 DatePicker 是一个摇摆组件,您可以将它添加到任何其他摇摆容器中,包括(在您的场景中)JTable 的单元格。
自动支持最常用的日期格式,如果需要,可以添加其他日期格式。
要强制执行所需的日期格式,您很可能希望将所选格式设置为 DatePicker 的默认“显示格式”。可以使用 Java 8 DateTimeFormatter Patterns指定格式。无论用户键入(或单击)什么,只要用户完成,日期总是会转换为指定的格式。
除了 DatePicker 之外,该库还具有 TimePicker 和 DateTimePicker 组件。我在下面粘贴了所有组件(和演示程序)的屏幕截图。
该库可以从项目发布页面安装到您的 Java 项目中。
项目主页位于 Github 上:
https ://github.com/LGoodDatePicker/LGoodDatePicker 。
Netbeans 中的另一种简单方法也可以在这里使用,Netbeans 本身内部有库,其中提供了针对此类情况的解决方案。也选择相关的。它更容易。按照链接中的规定步骤完成后,请重新启动 Netbeans。
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette. Lots of goodies here! Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)
打开您的 Java 源代码文档并导航到您在 Swing 类中创建的 JTable 对象。
创建一个包含 DatePickerTable 的新 TableModel 对象。您必须使用 MMDDYYYY 格式的日期值范围创建 DatePickerTable。第一个值是开始日期,最后一个值是结束日期。在代码中,这看起来像:
TableModel datePicker = new DatePickerTable("01011999","12302000");
在 datePicker 对象中设置显示间隔。默认情况下会显示每一天,但您可以设置一个固定的时间间隔。要在日期选项之间设置 15 天的间隔,请使用以下代码:
datePicker.interval = 15;
将您的表格模型附加到您的 JTable 中:
JTable newtable = new JTable (datePicker);
您的 Java 应用程序现在有一个下拉日期选择对话框。