Java Swing buttongroup clear on click - java

i have one button group with 2 radio buttons:
private javax.swing.JRadioButton jRadioButtonESPRINCIPAL;
private javax.swing.JRadioButton jRadioButtonESSECUNDARIO;
buttonGroup1 = new javax.swing.ButtonGroup();
I know that i can clear the group by buttonGroup1.clearSelection(), but i want to do this only if i click on a clicked radio button.
I have tried
private void jRadioButtonESPRINCIPALMouseClicked(java.awt.event.MouseEvent evt) {
if (jRadioButtonESPRINCIPAL.isSelected()) {
buttonGroup1.clearSelection();
}
else{
jRadioButtonESPRINCIPAL.setSelected(true);
}
}
private void jRadioButtonESSECUNDARIOMouseClicked(java.awt.event.MouseEvent evt) {
if (jRadioButtonESSECUNDARIO.isSelected()) {
buttonGroup1.clearSelection();
}
else{
jRadioButtonESSECUNDARIO.setSelected(true);
}
}
But didnt works
Any help will be appreciate

My previous answer was wrong sorry. You have to use ActionListeners like this:
jRadioButtonESPRINCIPAL.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//your code goes here
}
});
and then use a variable to store the last RadioButton that was selected. In the ActionListener you then have to check if the isSelected() equals the last selection. If yes, then use buttonGroup1.clearSelection();.
So the final code should look like this:
jRadioButtonESPRINCIPAL.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (jRadioButtonESPRINCIPAL.equals(lastSelectedRadioButton)) {
buttonGroup1.clearSelection();
lastSelectedRadioButton = null;
}
else {
lastSelectedRadioButton = jRadioButtonESPRINCIPAL;
}
}
});
jRadioButtonESSECUNDARIO.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (jRadioButtonESSECUNDARIO.equals(lastSelectedRadioButton)) {
buttonGroup1.clearSelection();
lastSelectedRadioButton = null;
}
else {
lastSelectedRadioButton = jRadioButtonESSECUNDARIO;
}
}
});

Related

enable a jcombobox without pressing enter

I am working in java swing in netbeans.
I have a textfield. I would like that a combobox will be enabled only if the text written in the textfield is greatter tahn one.
My code works if I press the enter key. But I would like to make it work just by writting in the textfield. How can I do this?
private void nmrintervTXTActionPerformed(java.awt.event.ActionEvent evt) {
String text = this.nmrintervTXT.getText();
System.out.println(text);
if (!text.isEmpty()) {
if (Integer.parseInt(text) > 1) {
this.evidenceOtherApplicantsTXT.setEnabled(true);
}
}
}
See addCaretListener API.
textfield.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
System.out.println("caretUpdate with new text: "+textfield.getText());
}
});
class MyDocumentListener implements DocumentListener {
#Override
public void insertUpdate(javax.swing.event.DocumentEvent e) {
update(e);
}
#Override
public void removeUpdate(javax.swing.event.DocumentEvent e) {
update(e);
}
#Override
public void changedUpdate(javax.swing.event.DocumentEvent e) {
}
public void update(javax.swing.event.DocumentEvent e) {
String text = nmrintervTXT.getText();
try {
evidenceOtherApplicantsTXT.setEnabled(Integer.parseInt(text) > 1);
} catch (NumberFormatException nfe) {
evidenceOtherApplicantsTXT.setEnabled(false);
}
}
}
public MyClass() {
initComponents();
}
#SuppressWarnings("unchecked")
nmrintervTXT = new javax.swing.JTextField();
nmrintervTXT.getDocument().addDocumentListener(new MyDocumentListener());
I think the parameter e was in fault in update in MyDocumentListener.

How to make an action command for same buttons

I have here just a snip of code for my button:
up = new JButton(new ImageIcon("more_buttons\\up3.png"));
up.setBackground(new Color(224,223,227));
up.setPreferredSize(new Dimension(5,15));
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000++;
if(value1000>0)
{
number.setText(value1000+"");
down.setEnabled(true);
}
}
});
down = new JButton(new ImageIcon("more_buttons\\down3.png"));
down.setBackground(new Color(224,223,227));
down.setPreferredSize(new Dimension(5,15));
down.setEnabled(false);
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000--;
if(value1000>0)
{
number.setText(value1000+"");
}
if(value1000==0)
{
number.setText(value1000+"");
down.setEnabled(false);
}
}
});
I'm wondering if I can make an action command for this button so that I won't have to repeat this code throughout my program. I only have to call the function like buttonaction(e) or something like that. I'm not used to creating action command but I have used it before but only for appending text. I'm not sure how to do that with a function like this. Is it possible? Or is there a more efficient way to do this?
You can add the same ActionListener to multiple buttons:
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// You can check which button was pressed and act accordingly
// simply by checking the event source:
if (e.getSource() == button1)
System.out.println("Button1 was pressed.");
else if (e.getSource() == button2)
System.out.println("Button2 was pressed.");
}
};
button1.addActionListener(al);
button2.addActionListener(al);
To remove boiler plate code, You need to at least implement an ActionListener in your class
samaple:
public class myClass implements ActionListener
It will generate an actionPerformed method After you need to add actionCommand in your button so when you click a button it will recognize it that you pressed that button
sample:
down.setActionCommand("down");
down.addActionListener(this);
up.setActionCommand("up");
up.addActionListener(this);
in the actionPerformed method
#Override
public void actionPerformed(ActionEvent evt)
{
String actionCommand = evt.getActionCommand(); //get the actionCommand and pass it to String actionCommand
switch(actionCommand) { //switch statement for each of the action command
case "down":
//down button command here
break;
case "up":
//up button command here
}
}
Take a look at How to use Actions
public abstract class AbstractNumberValueAction extends AbstractAction {
private NumberModel model;
private JTextField numberField;
private int delta;
public ValueAction(NumberModel model, JTextField numberField, int delta) {
this.model = model;
this.numberField = numberField;
this.delta = delta;
}
public void actionPerformed(ActionEvent evt) {
int value1000 = model.updateValue(delta);
if(value1000>0)
{
numberField.setText(value1000+"");
}
if(value1000==0)
{
numberField.setText(value1000+"");
setEnabled(false);
}
}
}
public class UpAction extends AbstractNumberValueAction {
public ValueAction(NumberModel model, JTextField numberField) {
this(model, numberField, 1);
putValue(SMALL_ICON, new ImageIcon("more_buttons\\up3.png"));
}
}
public class DownAction extends AbstractNumberValueAction {
public ValueAction(NumberModel model, JTextField numberField) {
this(model, numberField, -1);
putValue(SMALL_ICON, new ImageIcon("more_buttons\\down3.png"));
}
}
Which could then simply be applied as
up = new JButton(new UpAction(model, number));
down = new JButton(new DownAction(model, number));
For example...
(ps- NumberModel would be a simple class that controlled the underlying value to make is simpler to manage ;))

How to make two JButtons do separate actions

Everytime I press cancel or save on the UI it always executes both of the buttons. I've tried countless ways to make it listen to the if statements in the actionperformed block, but it seems to ignore it. I need it so that if I click save it only executes onSave() and cancel for onCancel(). Thanks for your time
public class EditTagPanel extends AbstractTagPanel implements ActionListener {
TagPanelEventListener tagPanelEventListener;
JButton save;
JButton cancel;
public EditTagPanel(ID3v1 id3v1Tag) {
super(id3v1Tag);
}
#Override
protected void configureActionFields() {
JPanel editOptionsPanel = new JPanel(new FlowLayout());
save = new JButton("Save");
save.addActionListener(this);
editOptionsPanel.add(save);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
editOptionsPanel.add(cancel);
this.add(editOptionsPanel, BorderLayout.PAGE_END);
}
public void addTagPanelEventListener(TagPanelEventListener tagPanelEvent) {
this.tagPanelEventListener = tagPanelEvent;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(save));
{
tagPanelEventListener.onSave(getId3v1Tag());
}
if(e.getSource().equals(cancel));
{
tagPanelEventListener.onCancel();
}
}
Just remove:
;
after each if-statment in your actionPerformed() method, like next:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(save)) {
tagPanelEventListener.onSave(getId3v1Tag());
}
if (e.getSource().equals(cancel)) {
tagPanelEventListener.onCancel();
}
}

Enable/disable a Java swing button in relation with a combo box

How can I update the state (enable/disable) of my button when the user changes the selected item in a combo box.?
The button has a reference to the combo box, but the combo box does not know anything about the button.
If the button has a reference to the combo box, then the button can register an action listener at the combo box in which you can change the state of your button.
final JButton button = new JButton();
final JComboBox comboBox = new JComboBox();
comboBox.addActionListener( new ActionListener() {
#Override
public void actionPerformed( final ActionEvent event ) {
// Your logic to determine when to enable/disable:
final boolean enabled = comboBox.getSelectedIndex() == 0;
button.setEnabled( enabled );
}
} );
The combobox is not required to know about the button. You need to add a listener to the combobox events like this:
public class ComboBoxDemo ... implements ActionListener {
. . .
petList.addActionListener(this) {
. . .
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
yourButton.setEnabled(true/false);
}
. . .
}
The JButton could simply add its own ActionListener on the JComboBox and in the ActionListener you could then change the state of the JButton according to the selected item of the combo box.
I have previously written code where enabling or disabling a button depends on filling a textfield and selecting an item of a combobox together. It may be helpful here.
jComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jComboBoxActionPerformed(e);
}
});
...
jTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void removeUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void changedUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
});
jTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextFieldActionPerformed(e);
}
});
...
private void jComboBoxActionPerformed(ActionEvent e){
if(jComboBox.getSelectedIndex() == -1)
jButton.setEnabled(false);
else if(!jTextField.getText().equals(""))
jButton.setEnabled(true);
}
private void jTextFieldDocumentListener(DocumentEvent e){
if(jTextField.getText().equals("") || jComboBox.getSelectedIndex() == -1){
jButton.setEnabled(false);
}
else{
jButton.setEnabled(true);
}
}
private void jTextFieldActionPerformed(ActionEvent e){
if(jTextField.getText().equals("")){
jButton.setEnabled(false);
}
if(!(jTextField.getText().equals(""))){
jButton.setEnabled(true);
}
}
If the combobox is selected and the textfield is filled, then the button will be enabled. Otherwise it will not be enabled.

Unable to get JFormattedTextField to highlight on mouse click focus event

I have been trying with no luck to get a JFormattedTextField to highlight on mouse click. I have been able to get it to work fine while tabbing through fields, however I would like to highlight everything on clicking.
I am only able to highlight on mouse click if I click and hold for about 1.5-2 seconds on the text field; I have no idea why.
I've searched and tried a few fixes including extending the class;
class HFTextField extends JFormattedTextField
{
HFTextField(MaskFormatter formatter)
{
super(formatter);
}
#Override
protected void processFocusEvent(FocusEvent e)
{
super.processFocusEvent(e);
if (e.getID() == FocusEvent.FOCUS_GAINED)
{
this.selectAll();
}
}
}
I am also defining a (rather verbose!) FocusListener which uses SwingUtilities.invokelater;
public static FocusListener CreateHighlightTextFieldFocusListener(final JTextField text_field)
{
FocusListener fl =
new FocusAdapter()
{
public void focusGained(FocusEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
text_field.selectAll();
}
});
}
};
return fl;
}
and this is the function that creates formatted text fields;
public static JTextField CreateFormattedTextField(int x, int y, int width, int height,
Method action_method, Method changed_method, Method remove_method,
Method update_method, String mask_formatter, String banned_chars)
{
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(mask_formatter);
} catch (ParseException e) {
assert(false);
}
if(banned_chars != null)
formatter.setInvalidCharacters(banned_chars);
JTextField text_field = new HFTextField(formatter);
text_field.setBounds(x, y, width, height);
if(action_method != null)
{
text_field.addActionListener(CreateTextFieldActionListener(action_method, text_field));
}
text_field.getDocument().addDocumentListener(
CreateTextFieldDocumentListener(changed_method, remove_method,
update_method, text_field));
text_field.addFocusListener(CreateHighlightTextFieldFocusListener(text_field));
return text_field;
Any help would be greatly appreciated!
maybe you have got problems with EDT,
how method you use for/how you added value to JTextField
works with JTextField, JFormateddTextField, with JComboBox too, and with AutoCompleted funcionalies http://www.java2s.com/Code/Java/Swing-JFC/AutocompleteTextField.htm
private FocusListener focsListener = new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
dumpInfo(e);
}
#Override
public void focusLost(FocusEvent e) {
//dumpInfo(e);
}
private void dumpInfo(FocusEvent e) {
//System.out.println("Source : " + name(e.getComponent()));
//System.out.println("Opposite : " + name(e.getOppositeComponent()));
//System.out.println("Temporary: " + e.isTemporary());
Component c = e.getComponent();
if (c instanceof JFormattedTextField) {
((JFormattedTextField) c).requestFocus();
((JFormattedTextField) c).setText(((JFormattedTextField) c).getText());
((JFormattedTextField) c).selectAll();
} else if (c instanceof JTextField) {
((JTextField) c).requestFocus();
((JTextField) c).setText(((JTextField) c).getText());
((JTextField) c).selectAll();
}
}
private String name(Component c) {
return (c == null) ? null : c.getName();
}
};
Try the following code
yourTextField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
yourTextField.selectAll();
}
});
}
});
I hate to give a simple answer, but have you tried using the MouseListener interface (or MouseAdapter class)?
Have you tried something like this:
fieldName.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JTextComponent text = (JTextComponent) e.getSource();
text.selectAll();
}
});
Also, I would not recommend doing this asynchronously.
If you want specialized behavior for a mouse click, then add a MouseAdapter to your JTextFiled, and in the mouseClicked event handler, explicitly alter the background.
basically you can use this code (not sure that for each formatter and input masks), but for Number, Date and String you can use following, with ensure that this JFormattedTextField doesn't implements AutoCompleted
myTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
myTextField.requestFocus();
myTextField.setText(myTextField.getText());
myTextField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
sure you can pack that into InvokeLate...

Categories