I am working with a java swing form that contains a JTextField. The text field needs input validation , validation is performed when the field losses focus . i.e clicking anyware apart from the field itself.
The form also contains a JButton to clear(cancel) the form . Now whenever I press the cancel button and the Textfield is the currently focused component the validation function is invoked. This should not happen.
I have tried InputVerifier and Focuslistener
Is there a way I can know what component caused the focus to change ?
This is fine but the form contains a JButton to clear(cancel) the form
You can use:
clearButton.setVerifyInputWhenFocusTarget(false);
to prevent the InputVerifier from being invoked when you click on the button.
You can use a FocusListener to react to a focusLost event. There you can retrieve the destination of the focus via getOppositeComponent() from the FocusEvent. If the destination is the clear/cancel/whatever button do nothing, otherwise validate.
A very basic example for this:
JTextField textField = new JTextField(15);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
Component comp = e.getOppositeComponent();
if (comp instanceof JButton) {
JButton button = (JButton) comp;
String buttonText = button.getText();
if (buttonText.equals("Cancel")) {
return;
}
}
// do the validation
System.out.println("validate");
}
});
Actually camickr's solution is a lot simpler than mine above. I had no idea that there was built in solution for this.
Related
Background Information: I am currently working in a Dialog class I have extended for my game. Inside of this dialog's content table I have both an Image and a Table (lets call it ioTable). Inside of ioTable I have a combination of both Labels and TextFields. The idea is that the dialog becomes a sort of form for the use to fill out.
Next, inside of the Dialog's button table, I want to include a "Clear" TextButton (clearButton). The idea that clearButton will clear any values written to the TextFields of ioTable.
My Question: Is is possible to add a listener to each of the TextFields of ioTable that will trigger when clearButton is pressed. As always, any other creative solution is more than welcome.
You could just give the EventListener a reference to the table you want to clear:
// Assuming getSkin() and ioTable are defined elsewhere and ioTable is final
TextButton clearButton = new TextButton("Clear", getSkin());
clearButton.addListener(new EventListener() {
#Override
public boolean handle(Event event) {
for(Actor potentialField : table.getChildren()) {
if(potentialField instanceof TextField) {
((TextField)potentialField).setText("");
}
}
return true;
}
});
// Add clearButton to your dialog
If you see yourself creating multiple clearButtons, you could easily wrap this in a helper method or extend TextButton.
I have an application that is developed in Java swing and the NetBens 7 IDE
Steps:
I want to use a Jbutton to perform two different functions depending on the user mode.
for example I want to label a single button with the following text "New Record" and
"Exit New Record"
The default text is the "New Record". This will enable the user enter new record.
Whiles in the new record mode, the text on the jButton changes to "Exit New Record".
To exit the new record mode the user clicks on the same button to exit.
This will then change the text on button to the default enter "Enter New Record"
Is there any suggestion on how to do this with the netbeans IDE or do I manually
override a method?
Implement Action Listener on JButton (code not tested, just for your hint):
public class MyButton extends JButton implements ActionListener{
boolean pressed = false;
public MyButton(String name){
super(name);
this.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
if(pressed){
pressed = !pressed;
_change_text_on_button_
_do_job_
}
}
Than use customized MyButton.
As shown in examples here and here, a button's text can be changed in its ActionListener. The NetBeans GUI editor generates the code to invoke the ActionListener, but it lets you edit the code in the method that is called. The method name will be something like nameActionPerformed().
See also How to Use Buttons, Check Boxes, and Radio Buttons and this suggestion.
I'm trying to implement a simple window that contain two buttons Yes and No.
When clicking on Yes I want to disable the No button and when pressing on No I want to disable the Yes button.
I've implemented:
JButton btnYes = new JButton("Yes");
contentPane.add(btnYes);
btnYes.setActionCommand("Yes");
btnYes.addActionListener(this);
...the same for the No button...
Now I'm catching the event in this method:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Yes"))
{
//I know how to get the button that caused the event
//but I don't know how to disable the OTHER button.
JButton source = (JButton)e.getSource();
//Handle the source button...
}
}
In the above method I have an access to the button that caused the event, but not to the other button.
What is the best way of getting the buttons?
You should just implement ActionListener as a nested class of your Dialog's class, in this case you will have full access to all fields of outer class (in which you should store reference to buttons when your create them).
The bad dirty solution (that should NOT be used) still exists: to navigate to battens through getParent() of JButton and then through getChildren() of parents childrens. Just to show that it is possible anyway.
You could use a JButton array as class member variable and to check which instance didnt cause the event:
for (JButton button: buttonArray) {
if (button != source) {
button.setEnabled(false); // disable the other button
}
}
I have two JComboBox and one button. I am trying to do that if I select an item from the two combo box individually and press the button called search. Then the two selected items from the two combo box will save in a new two separate string.
Please anyone help me to solve the problem.
Here is the code snippet
//here is the strings that in the combo box
String lc[] = {"Kolabagan-Dhaka", "Gabtoli-Dhaka", "Fakirapul-Dhaka", "Shaymoli-Dhaka"};
String rc[] = {"Banani-Bogra", "Rangpur","Shatrasta-Bogra"};
//here is my two jcombo box
JComboBox lcCombo = new JComboBox(lc);
JComboBox rcCombo = new JComboBox(rc);
// here is my search button
JButton searchButton = new JButton("Search");
There are two ways to go about this. The first is to have one class that implements ActionListener and in the implementation, check the source (ActionEvent.getSource()). Based on which component sourced the event, you take the appropriate action.
The other option (and my preference) is to create an ActionListener for each component that requires one. You can use anonymous classes if you don't want to explicitly define one for each case. This way each listener knows exactly what component caused the event and what action to take.
Example:
JComboBox lcCombo = new JComboBox(lc);
lcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do left stuff
}
});
JComboBox rcCombo = new JComboBox(rc);
rcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do right stuff
}
});
To expand on unholysampler, once you have the ActionListener working you can use lcCombo.getSelectedIndex() to check which item has been selected.
What I am hoping is, when typing in editable JCombobox , the Popup Menu of the JCombobox to appear autumaticaly , i did this and it worked . But, when i changed the Icon of the Arrow Button in the JCombobox it didnt worked any more as shown in the picture
before changing Arrow Button Icon
After changing Arrow Button Icon (the Popup never appears, when one writes in the JCombobox)
this is what i did :
JTextComponent editor;
/** Creates new form combo */
public combo() {
initComponents();
editor = (JTextComponent) jComboBox1.getEditor().getEditorComponent();
jComboBox1.setEditable(true);
editor.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
char keyChar = e.getKeyChar();
if (jComboBox1.isDisplayable())
{
jComboBox1.setPopupVisible(true);
}
editor.setCaretPosition(editor.getText().length());
// System.out.println("wwwweeeee"+keyChar);
}
});
jComboBox1.setUI(new SynthComboBoxUI() {
protected JButton createArrowButton() {
JButton btn = new JButton();
btn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/error3.png")));
return btn;
}
});
}
Pleeeese help because i'm really tired from searching for a solution
The technical problem here is that the editor is created/maintained by the ui. When setting a custom ui it is replaced by a new editor, so you are listening to a component that is no longer part of the container hierarchy.
After digging a bit ... I still don't have a solution :-( On face value, you'd call setUI before installing the listener on the editor - BUT calling setUI is always wrong ... so simply don't.
Seeing that the ui is synth-based, the correct way to update its visual fore/background properties is to supply custom painters, per-application or per-instance. Nimbus specifically allows to install per-instance custom UIDefaults via the "Nimbus.Overrides" client property. For changing the icon on the arrow button, the appropriate override would be
Painter core = // a custom painter which paints the icon
comboDefaults.put("ComboBox:\"ComboBox.arrowButton\"[Enabled].foregroundPainter", core);
combo.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
combo.putClientProperty("Nimbus.Overrides", comboDefaults);
All fine, except not working - looks like the overrides are not properly installed on the children.
Edit 2
... hours later ...
from all available resources, the above should work, see f.i. Jasper's initial explanation of how-to define custom properties:
ComponentA:ChildComponentB.foreground which lets you specify a ChildComponentB contained within ComponentA.
So I suspect it's really a bug. A not really satisfying hack-around is to install the override on the button itself:
JButton org = null;
for (int i = 0; i < combo.getComponentCount(); i++) {
if (combo.getComponent(i) instanceof JButton) {
org = (JButton) combo.getComponent(i);
UIDefaults buttonDefaults = new UIDefaults();
buttonDefaults.put("ComboBox:\"ComboBox.arrowButton\"[Enabled].foregroundPainter", painter);
org.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
org.putClientProperty("Nimbus.Overrides", buttonDefaults);
break;
}
}
That's not satisfying at all, as the button creation is controlled by the ui delegate, so this config will not survive a switch of LAF. Or the other way round: you'll need a install a PropertyChangeListener with the UIManager and on detecting a switch to Nimbus, manually copy the overrides from the combo to its children.