How to use com.toedter.calendar.JDateChooser? - java

I'm using com.toedter.calendar.JDateChooser to search between two dates so I've two jDateChooser components.
jDateChooser1 and jDateChooser2 I want retrieve record after select date from second jDateChooser2 in jTable
I tried write code in constructor it doesn't compile cause empty
String from = jDateChooser1.getDate(); gets null
I can use jButton to search records but I want it on jDateChooser event.
To check if it is working I tried
private void jDateChooser1MouseClicked(java.awt.event.MouseEvent evt){
jLabel1.setText(String.valueOf(jDateChooser1.getDate()));
}
and
private void jDateChooser1MouseReleased(java.awt.event.MouseEvent evt){
jLabel1.setText(String.valueOf(jDateChooser1.getDate()));
}
But it doesn't working either with
jDateChooser1MouseReleased(java.awt.event.MouseEvent evt)
or
jDateChooser1MouseClicked(java.awt.event.MouseEvent evt)
It's working with jButton as I mentioned above but I don't want to use:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText(String.valueOf(jDateChooser1.getDate()));
//Working
}
So my previous title was "How implement event for com.toedter.calendar.JDateChooser?"
So now my question is more clear to understand.
Thank you.

You can register a listener using dateChooser.getDateEditor().addPropertyChangeListener(). Then listen for changes in property "date". Try below sample code.
import com.toedter.calendar.JDateChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class JDateChooserSample
{
public static void main(String[] args)
{
JLabel label = new JLabel("No date");
JDateChooser dateChooser = new JDateChooser();
dateChooser.getDateEditor().addPropertyChangeListener(new PropertyChangeListener()
{
#Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals("date"))
{
label.setText(String.valueOf(dateChooser.getDate()));
}
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new GridLayout(2, 1));
f.getContentPane().add(dateChooser);
f.getContentPane().add(label);
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}

Related

Trying to make a JButton visible when a JTextField is tabbed out [duplicate]

I am trying to make a text adventure game that includes puzzles in every room. I have direction buttons to go to the next rooms, but I want the buttons to display a message if they haven't answered the question correctly yet. When they answer it then the game will show them which way they can go and the buttons will work. Is there anyway to do this?
I tried doing this, but the only way this works is if they type the answer and leave it in the textfield instead of typing enter. I don't want that though.
private void northBtnMouseClicked(java.awt.event.MouseEvent evt) {
if(!playerInput.getText().equals(currentRoom.getAns()))
{
gameScreen.append("\nThe doors are locked until you answer the puzzle.");
}
else
{
String direction = "north";
Room nextRoom = currentRoom.getExits(direction);
if(nextRoom == null)
{
gameScreen.append("\n There is not an exit that way\n");
}
else
{
currentRoom = nextRoom;
gameScreen.append("\n" + currentRoom.getLongDescription());
}
}
}
There a number of ways this might be achieved, one of the simplest might be to simply disable the button(s) until the user enters what you want.
The (minor) problem with this is that it will require the user to press the "action" key (typically Enter) until the input can be validated. Not a big deal, but its not always obvious to the user.
Another approach would be to use a DocumentListener to monitor for changes to the underlying Document and validate the input in real time.
This approach allows you to provide real time feedback to the user as they type. It also allows the user to paste content into the field and have it validated as well, which is not done if you use a KeyListener.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TestDoc {
public static void main(String[] args) {
new TestDoc();
}
public TestDoc() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField field;
private JButton button;
public TestPane() {
button = new JButton("Make it so");
button.setEnabled(false);
field = new JTextField(10);
field.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
validateInput();
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(field, gbc);
add(button, gbc);
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
validateInput();
}
#Override
public void removeUpdate(DocumentEvent e) {
validateInput();
}
#Override
public void changedUpdate(DocumentEvent e) {
validateInput();
}
});
}
public void validateInput() {
String text = field.getText();
if ("go".equals(text)) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
}
}
Have a look at Listening for Changes on a Document for more details
I just give you this example to give you an idea and start you up
Code:
public class NewClass {
public static void main(String... args) {
JButton jb = new JButton("Enter");
jb.setEnabled(false);
JTextField jt = new JTextField(15);
JFrame jf = new JFrame();
jf.setSize(200, 100);
FlowLayout layout = new FlowLayout();
jf.setLayout(layout);
jf.add(jb);
jf.add(jt);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jt.addKeyListener((new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
if(!textField.getText().isEmpty())
jb.setEnabled(true);
else
jb.setEnabled(false);
}
}));
}
}
output:
Explanation:
There are many ways to accomplish what you want. For example, Key Listener and Document Listener.
The good practice is to use Document Listener because it is not depended on activities.
Note: there are other good ways to solve your issue but I thought this way is more easier for you to understand
Take a look at this comment
A DocumentListener would be better as that lets you react to any
changes to the text, whether or not they were triggered by a key press
(e.g. a paste from the clipboard), and you don't have to worry about
key presses that don't cause the text to change. – Ian Roberts
Source: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Using Document Listener Approach which is good practice and recommended
Code:
import java.awt.FlowLayout;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.Document;
public class DocumentListenerSample {
public static void main(String args[]) {
JButton jb = new JButton("Enter");
jb.setEnabled(false);
JTextField jt = new JTextField(15);
JFrame jf = new JFrame();
jf.setSize(200, 100);
FlowLayout layout = new FlowLayout();
jf.setLayout(layout);
jf.add(jb);
jf.add(jt);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
DocumentListener documentListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
Document source = documentEvent.getDocument();
int length = source.getLength();
if(length != 0)
jb.setEnabled(true);
else
jb.setEnabled(false);
}
};
jt.getDocument().addDocumentListener(documentListener);
jf.setSize(250, 150);
jf.setVisible(true);
}
}
Sure, you could either jbtn.setEnabled(false) until you had all your answers or (probably easier) keep an answer count accessible to your MouseClicked routine that simply ignores clicks until the questions are answered.

How to Display Message When i left JTextField in java

Actually i'm writing code. I want to display message dialogue (without pressing any button) when I left my JTextField but don't know how to do this. Please Help. Im using NetBeans.
You can use Focus Listener API to achieve that.
On focusLost event, you can show your dialog box.
Example from the documentation:
public void focusLost( FocusEvent e )
{
displayMessage( "Focus lost", e );
}
You can use FocusListener class focusLost() method.
Simple Example:
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ExampleClass {
JFrame MainFrame;
JTextField textField1;
JTextField textField2;
public ExampleClass(){
MainFrame = new JFrame("Example");
MainFrame.setLayout(new FlowLayout());
textField1 = new JTextField(10);
textFieldFocus();
textField2 = new JTextField("Dummy text");
MainFrame.add(textField1);
MainFrame.add(textField2);
MainFrame.pack();
MainFrame.setVisible(true);
}
private void textFieldFocus() {
textField1.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
JOptionPane.showMessageDialog(null, "Done!");
}
#Override
public void focusGained(FocusEvent e) {}
});
}
public static void main(String[] args) {
new ExampleClass();
}
}

Selecting / highlighting text in a JTextArea belonging to a JOptionPane

My problem is the following: In my application the user clicks a button which brings up a dialog box (a custom jOptionPane). This dialog contains a JTextArea in which the user will type a response, which will then be processed by the application, however I would like this JTextArea (which will hold the user's input and currently contains example text like "Write your answer here") to be automatically highlighted.
I can do this normally, by calling requestFocusInWindow() followed by selectAll() on the JTextArea however there seems to be a problem when this is done using a JOptionPane which I'm guessing is to do with the fact that the focus cannot shift to the JTextArea successfully.
I've made a SSCCE to demonstrate this clearly, and hopefully get an answer from one of you guys as to how I can make this possible. Thanks in advance!
Class 1/2 : Main
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
Main main = new Main();
main.go();
}
private void go() {
JPanel background = new JPanel();
JPanel mainPanel = new ExtraPanel();
((ExtraPanel) mainPanel).setupPanel();
JButton testButton = new JButton("Test the jOptionPane");
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
optionPaneTest();
}
});
background.add(mainPanel);
background.add(testButton);
getContentPane().add(background);
pack();
setVisible(true);
}
private void optionPaneTest() {
JPanel testPanel = new ExtraPanel();
((ExtraPanel) testPanel).setupPanel();
int result = JOptionPane.showConfirmDialog(null, testPanel,
"This is a test", JOptionPane.OK_CANCEL_OPTION);
}
}
----------------------------------------------------------------------------- Class 2/2 : ExtraPanel
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ExtraPanel extends JPanel{
public void setupPanel() {
JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.requestFocusInWindow();
textArea.selectAll();
add(textArea);
}
}
Just add
textArea.getCaret().setSelectionVisible(true)
After textArea.selectAll();
If you want focus in the TextArea so that the user can immediately start typing, you can trigger the selection using the ancestor added event.
public void setupPanel() {
final JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.addAncestorListener(new AncestorListener() {
public void ancestorRemoved(AncestorEvent event) { }
public void ancestorMoved(AncestorEvent event) { }
public void ancestorAdded(AncestorEvent event) {
if (event.getSource() == textArea) {
textArea.selectAll();
textArea.requestFocusInWindow();
}
}
});
add(textArea);
}

Login is not working in java JPanel?

I am trying to create a login in java using a java jpanel. However my code does not work, as it does not print out "worked" as it is supposed to when the user clicks continue after typing "pass" into the textfield and I do not understand why? Here is my code, thank you in advance:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class login implements ActionListener {
public JTextField x = new JTextField(10);
public JFrame f = new JFrame("Login");
public JButton B = new JButton("continue");
public login()
{
f.add(new JLabel("Login"));
f.add(x);
B.addActionListener(this);
f.add(B);
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String textFieldValue = x.getText();
if(textFieldValue=="pass")
{
System.out.println("worked!");
}
}
public static void main(String[] args) {
new login();
}
}
I have also tried to use the password as a string, like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class login implements ActionListener {
public JTextField x = new JTextField(10);
public JFrame f = new JFrame("Login");
public JButton B = new JButton("continue");
String pass;
public login()
{
f.add(new JLabel("Login"));
f.add(x);
B.addActionListener(this);
f.add(B);
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
pass="pass";
}
public void actionPerformed(ActionEvent e)
{
String textFieldValue = x.getText();
if(textFieldValue==pass)
{
System.out.println("worked!");
}
}
public static void main(String[] args) {
new login();
}
}
for string comparisons in Java you should use the String#equals(String s) method, not the "==" operation. The equals(...) method tests to see if two Strings hold the same characters in the same order (what you desire). The == operation tests if the objects referred to by two String variales are one and the same (not what you desire).
This could be the problem, but your question is not that clear

Display the item name on the table in a JLabel

I want to put the name of the item that I selected in a JTable in a JLabel that every time that i click a new item in the table the text in the JLabel also change
can someone tell me what should I learn in java to produce that?
You should know very basic Swing programming, and a little deeper understanding of a TableModel, SelectionModel and ListSelectionListener (which is the key to your goal).
A working example:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TableSelectionToLabel {
private static JTable t = new JTable(new String[][]{{"1,1", "1,2"}, {"2,1", "2,2"}},
new String[]{"1", "2"});
private static JLabel l = new JLabel("Your selction will appear here");
private static JFrame f = new JFrame("Table selection listener Ex.");
private static ListSelectionListener myListener = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int col = t.getColumnModel().getSelectionModel().getLeadSelectionIndex();
int row = t.getSelectionModel().getLeadSelectionIndex();
try {
l.setText(t.getModel().getValueAt(row, col).toString());
} catch (IndexOutOfBoundsException ignore) {
}
}
};
public static void main(String[] args) {
t.getSelectionModel().addListSelectionListener(myListener);
t.getColumnModel().getSelectionModel().addListSelectionListener(myListener);
f.getContentPane().add(t, BorderLayout.NORTH);
f.getContentPane().add(l, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
EDIT:
I modified the code to listen to both selection events from the model AND the column model to get a more accurate outcome.
First create the JLabel:
JLabel label = new JLabel();
Then add a listener to the table for selections:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
label.setText(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
});

Categories

Resources