Question

I have a JTextField represents a day in a week, such as "Friday", when I click on it, I want to have a choice such as "1st of month, 3rd of month or last of month", so I came up with two options :

<1> Hold down a number or letter, let's say "2" or "L", then click on "Friday" means 2nd (or last) Friday of the month, in this case, how to get the number while mouse clicks on the JTextField ?

<2> Right mouse click on the "Friday" JTextField, drop down a menu, with either buttons or checkboxes that let me choose, then close the menu and get the value.

My code look like this so far :

  private final JTextField[] dayHeadings=new JTextField[]{new JTextField("Su"),
                                                          new JTextField("Mo"),
                                                          new JTextField("Tu"),
                                                          new JTextField("We"),
                                                          new JTextField("Th"),
                                                          new JTextField("Fr"),
                                                          new JTextField("Sa")};
......

    for (int ii=0; ii < dayHeadings.length; ii++)
    {
      dayHeadings[ii].setEditable(false);
      dayHeadings[ii].setFocusable(false);
      dayHeadings[ii].addMouseListener(new MouseAdapter() { public void mouseClicked(final MouseEvent evt) { onHeadingClicked(evt); } });
      add(dayHeadings[ii],new AbsoluteConstraints(x,38,X_Cell_Size+1,Y_Cell_Size+1));
    }
......
  void onHeadingClicked(final java.awt.event.MouseEvent evt)
  {
    final javax.swing.JTextField fld=(javax.swing.JTextField) evt.getSource();

    ...
  }

How to do either of the above, are they doable in Java ?

Was it helpful?

Solution

Option 1:

There is no way to do this in one step. You would need to add a KeyListner to track whenever a key is pressed and then save the character value. Then you would need to add a MouseListener to listener for mousePressed events. When the mousePressed event fires you would need to to check which character is saved and then do your processing. Therefore your listener would to implement both the KeyListener and MouseListener interfaces.

Option 2:

You need to add a mouse listener and listen for a right mouse click, then display a popup menu.

I think option 2 is more intuitive and more easily done. Its always easier to work with one hand then be forced to use two hands.

OTHER TIPS

getModifiers is actually that what I needed. a sample for the modifiers can be found here

Another, lazier way to do it would be using getModifiers() on the mouseclick event. It shows which modifier keys (ctrl, alt, shift, etc), if any, were pressed during the mouse click. Using these buttons isn't as intuitive as a drop down menu or numbers in my opinion, but could work.

Read more here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top