- Swing Examples — Using Date Format in JFormattedTextField
- Example
- Output
- Java Swing Date Picker Example
- 1. Introduction
- 2. JAVA Swing
- 2.1 MVC Architecture
- 2.2 Swing Features
- 2.3 Setup
- 2.4 Class and description
- 2.5 SWING UI Elements
- 3. Java Swing Date Picker
- 3.1 Code
- 3.2 Output
- 4. Download
- JavaFX 8 DatePicker в приложении Swing
- 1.1. Исходный код
- 2. Описание приложения
- 2.1. Элемент управления DatePicker
- 2.2. Проверка даты
Swing Examples — Using Date Format in JFormattedTextField
Following example showcase how to create and use JFormattedTextField to specify a Date format on Text Fields in Swing based application.
We are using the following APIs.
- JFormattedTextField − To create a formatted text field.
- DateFormat − To provide Date format to JFormattedTextField.
- SimpleDateFormat(patten) − to get a desired date format of date pattern.
Example
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.LayoutManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingTester implements PropertyChangeListener < private static JFormattedTextField principleTextField; private static JFormattedTextField rateTextField; private static JFormattedTextField yearsTextField; private static JFormattedTextField amountTextField; public static void main(String[] args) < SwingTester tester = new SwingTester(); createWindow(tester); >private static void createWindow(SwingTester tester) < JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame, tester); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); >private static void createUI(final JFrame frame, SwingTester tester) < JPanel panel = new JPanel(); LayoutManager layout = new GridLayout(6,2); panel.setLayout(layout); panel.setSize(300, 200); panel.setBorder(BorderFactory.createTitledBorder("Formats")); NumberFormat principleFormat = NumberFormat.getNumberInstance(); principleTextField = new JFormattedTextField(principleFormat); principleTextField.setName("Principle"); principleTextField.setColumns(10); JLabel principleLabel = new JLabel("Principle:"); principleLabel.setLabelFor(principleTextField); principleTextField.setValue(new Double(100000)); principleTextField.addPropertyChangeListener("value", tester); NumberFormat rateFormat = NumberFormat.getPercentInstance(); rateFormat.setMinimumFractionDigits(2); rateTextField = new JFormattedTextField(rateFormat); rateTextField.setName("Rate"); rateTextField.setColumns(10); JLabel rateLabel = new JLabel("Interest Rate:"); rateLabel.setLabelFor(rateTextField); rateTextField.setValue(new Double(0.1)); rateTextField.addPropertyChangeListener("value", tester); yearsTextField = new JFormattedTextField(); yearsTextField.setName("Years"); yearsTextField.setColumns(10); JLabel yearLabel = new JLabel("Year(s):"); yearLabel.setLabelFor(yearsTextField); yearsTextField.setValue(new Double(1)); yearsTextField.addPropertyChangeListener("value", tester); NumberFormat amountFormat = NumberFormat.getCurrencyInstance(); amountTextField = new JFormattedTextField(amountFormat); amountTextField.setName("Amount"); amountTextField.setColumns(10); amountTextField.setEditable(false); JLabel amountLabel = new JLabel("Amount:"); amountLabel.setLabelFor(amountTextField); amountTextField.setValue(new Double(110000)); DateFormat dateFormat = new SimpleDateFormat("dd MMM YYYY"); JFormattedTextField today = new JFormattedTextField(dateFormat); today.setName("Today"); today.setColumns(10); today.setEditable(false); JLabel todayLabel = new JLabel("Date:"); todayLabel.setLabelFor(today); today.setValue(new Date()); panel.add(principleLabel); panel.add(principleTextField); panel.add(rateLabel); panel.add(rateTextField); panel.add(yearLabel); panel.add(yearsTextField); panel.add(amountLabel); panel.add(amountTextField); panel.add(todayLabel); panel.add(today); JPanel mainPanel = new JPanel(); mainPanel.add(panel); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); >@Override public void propertyChange(PropertyChangeEvent evt) < double amount, rate, years, principle; principle = ((Number)principleTextField.getValue()).doubleValue(); rate = ((Number)rateTextField.getValue()).doubleValue() * 100; years = ((Number)yearsTextField.getValue()).doubleValue(); amount = principle + principle * rate * years / 100; amountTextField.setValue(new Double(amount)); >>
Output
Java Swing Date Picker Example
Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way.
1. Introduction
- A single API is to be sufficient to support multiple look and feel.
- API is to model driven so that highest level API is not required to have the data.
- API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.
2. JAVA Swing
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton , JTextField , JTextArea , JRadioButton , JCheckbox , JMenu , JColorChooser etc.
2.1 MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
- A Model represents component’s data.
- View represents visual representation of the component’s data.
- Controller takes the input from the user on the view and reflects the changes in Component’s data.
- Swing component has Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.
Every user interface considers the following three main aspects:
- UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
- Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
- Behavior: These are events which occur when the user interacts with UI elements.
2.2 Swing Features
- Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
- Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
- Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
- Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.
2.3 Setup
- Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
- NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
- Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org
Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.
2.4 Class and description
- Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation.
- Container: A Container is a component that can contain other SWING components.
- JComponent: A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent , component must be in a containment hierarchy whose root is a top-level Swing container.
2.5 SWING UI Elements
- JLabel A JLabel object is a component for placing text in a container.
- JButton This class creates a labeled button.
- JColorChooser A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
- JCheck Box A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.
- JRadioButton The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.
- JList A JList component presents the user with a scrolling list of text items.
- JComboBox A JComboBox component presents the user with a to show up menu of choices.
- JTextField A JTextField object is a text component that allows for the editing of a single line of text.
- JPasswordField A JPasswordField object is a text component specialized for password entry.
- JTextArea A JTextArea object is a text component that allows for the editing of a multiple lines of text.
- ImageIcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images.
- JScrollbar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
- JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.
3. Java Swing Date Picker
In this section, you will learn how to display date picker using java swing. The date picker lets the user select the Date through an easy interface that pops up with a Calendar. The user can navigate through the Calendar and select a date. It contains an editable date picker, a date field, a multiple month calendar and a month component. You can select any date from the Date Picker.
3.1 Code
Code for the following will look the one below.
package swing_1; import java.awt.*; import java.awt.event.*; import javax.swing.*; class DatePicker < int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH); int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);; JLabel l = new JLabel("", JLabel.CENTER); String day = ""; JDialog d; JButton[] button = new JButton[49]; public DatePicker(JFrame parent) < d = new JDialog(); d.setModal(true); String[] header = < "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" >; JPanel p1 = new JPanel(new GridLayout(7, 7)); p1.setPreferredSize(new Dimension(430, 120)); for (int x = 0; x
3.2 Output
- After execution of code, output will look like the one below.
- After clicking on the button Popup a calendar will appear.
- click on a particular date to make a selection
4. Download
This was an example of Java Date Picker Example.
JavaFX 8 DatePicker в приложении Swing
В этой статье показан пример приложения Java SE 8 Swing, использующего DatePicker управления JavaFX 8 DatePicker .
DatePicker управления DatePicker позволяет пользователю вводить дату в виде текста или выбирать дату во всплывающем календаре. В этом примере используется Swing JFrame с элементами управления FX. Для встраивания содержимого FX в приложение javafx.embed.swing пакет javafx.embed.swing предоставляет класс JFXPanel .
Приложение берет введенную дату из средства выбора даты и проверяет, находится ли оно в выбранном пользователем диапазоне дат (от и до даты) из двух средств выбора даты. Проверка даты выбора даты включает в себя:
- Дата от меньше даты
- Даты не из будущего
- Дата ввода находится в пределах от и до даты (включая)
Недопустимые или действительные сообщения отображаются в диалоговых окнах FX Alert .
На следующих двух FXPanel экрана показано приложение с JFrame и встроенными элементами управления FX ( FXPanel с DatePicker , DatePicker и Button ) и DatePicker календарем DatePicker соответственно.
FX контролирует в Swing JFrame
FX DatePicker с всплывающим календарем
1.1. Исходный код
Исходный код для этого примера FXDatePickerInSwingExample.java доступен для загрузки по ссылке, приведенной в конце этой статьи. Обратите внимание, что Java SE 8 требуется для компиляции и запуска кода. Java SE 8 включает в себя JavaFX 8.
2. Описание приложения
Приложение Java Swing FXDatePickerInSwingExample запускается из метода main() программы Java SE в потоке диспетчеризации событий следующим образом:
Метод initAndShowGUI() отображает Swing JFrame со встроенными в него элементами управления JavaFX. Следующий фрагмент кода показывает конструкцию JFrame :
javafx.embed.swing.JFXPanel является компонентом для встраивания содержимого JavaFX в приложения Swing и обеспечивает совместимость JavaFX и Swing. JFXPanel расширяет JFXPanel javax.swing.JComponent . Отображаемый контент указывается с помощью JFXPanel setScene() который принимает экземпляр javafx.scene.Scene . Этот метод вызывается в потоке диспетчеризации событий приложения FX следующим образом:
Метод createScene() возвращает экземпляр Scene с элементами управления FX. Скриншоты, показанные выше, имеют законченный графический интерфейс. В следующем фрагменте кода показан метод createScene() с фрагментами кода:
2.1. Элемент управления DatePicker
javafx.scene.control.DatePicker управления javafx.scene.control.DatePicker позволяет пользователю вводить дату в виде текста или выбирать дату во всплывающем календаре. Свойство DatePicker представляет LocalDate выбранный LocalDate . Это свойство может использоваться с конструктором, а также имеет методы getValue() и setValue() .
Следующий фрагмент кода создает объект выбора даты и устанавливает его значение на сегодняшнюю дату: DatePicker picker = new DatePicker(LocalDate.now());
2.2. Проверка даты
В этом приложении есть три сборщика даты. Все они настроены на сбор действительных дат:
- Значения даты не могут быть больше, чем сегодня.
- Дата начала никогда не может быть после даты.
Для выполнения этих ограничений используется dayCellFactoryProperty DatePicker . Можно настроить собственную фабрику ячеек для настройки отдельных ячеек дня во всплывающем окне выбора даты. У средства выбора даты есть метод для установки фабрики пользовательских ячеек: setDayCellFactory() .
Эти API используются для создания собственной фабрики ячеек: класс DateCell используется DateCell даты для визуализации отдельных ячеек сетки в календарном месяце. Приложение может переопределить метод update DateCell чтобы изменить свойства каждой ячейки, такие как текст, цвет фона и т. Д.
В следующем фрагменте кода показан метод, который возвращает пользовательский dayCellFactory . Обратите внимание, что этот единственный метод возвращает фабрику ячеек для трех сборщиков дат.