CheckBox dead loop listener - java

I have the following listeners:
mListener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
setRequired(true);
} else {
setRequired(false);
}
getTableSteps().repaint();
}
};
myCheckBox.addItemListener(mListener);
for (int i = 0; i < mTableSteps.getRowCount(); i++) {
((JCheckBox) mTableSteps.getCellRenderer(i, 0)).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
myCheckBox.setSelected(false);
}
});
}
As you can see, myCheckBox is the checkbox which if it is modified, modifies some of the checkboxes from the first column of mtablesteps (this is done in the setRequired method). Also, if one of the checkboxes from mtablesteps column 0 are modified they should put myCheckBox to not being selected.
Now the problem is when I first select myCheckBox it triggers the listener and selects some checkboxes from mTableSteps. But when these checkboxes are selected, they also trigger their listener and deselect myCheckBox. Thus, myCheckBox always gets deselected.
I hope this makes sense. Any suggestions on how to avoid this are appreciated.
To be more even more clear, what I'm trying to achieve is have a listener for myCheckBox which when the checkbox is selected it will select some of the checkboxes from the first column of mTableSteps. But also, if I select/deselect a checkbox from the table, it will put myCheckBox to not selected. Thanks a lot.

You need some kind of state flag that you can use to tell the child listeners if they should process the event of not.
mListener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
ignoreUpdates = true
try {
if (((JCheckBox) e.getSource()).isSelected()) {
setRequired(true);
} else {
setRequired(false);
}
getTableSteps().repaint();
} finally {
ignoreUpdates = false;
}
}
}
myCheckBox.addItemListener(mListener);
for (int i = 0; i < mTableSteps.getRowCount(); i++) {
((JCheckBox) mTableSteps.getCellRenderer(i, 0)).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (!ignoreUpdates) {
myCheckBox.setSelected(false);
}
}
});
}
Hope that helps

Related

Checkbox disabled Combobox in Java [duplicate]

How can I make the comboBox available when the checkBox was uncheck (vice versa)
Why the comboBox is still disable after I unChecked the checkBox?
choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
...
a.addActionListener(this);
chk.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
//disable the a comboBox when the checkBox chk was checked
if(e.getSource()==chk)
a.setEnabled(false);
//enable the a comboBox when the checkBox chk was unchecked
else if(e.getSource()!=chk)
a.setEnabled(true);
}
If I understand you correctly I think all that you need to do is to change the enabled state of the combo box based on the current value of the checkbox:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==chk) {
a.setEnabled(chk.isSelected());
}
}
I have a similar set up, and I use an Item Listener, like so:
CheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED){
ComboBox.setEnabled(true);
}else if(e.getStateChange()==ItemEvent.DESELECTED){
ComboBox.setSelectedIndex(-1);
ComboBox.setEnabled(false);
}
}
});
This way the behaviour is different when selected and deselected.
I treid this and worked..
public class JF extends JFrame implements ActionListener {
String choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
JF()
{
this.add(a, BorderLayout.NORTH);
this.add(chk, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
a.addActionListener(this);
chk.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
//NOTE THE FOLLOWING LINE!!!!
if(e.getSource()==chk)
a.setEnabled(chk.isSelected());
}
public static void main(String[] args) {
new JF().setVisible(true);
}
}
Your old code didn't work because, even unchecking a checkbox triggers the event. The source of the trigger is the checkbox.. so both while checking and unchecking the event source was chk
if (e.getSource() == chckbxModificar) {
if (chckbxModificar.isSelected()) {
cbxImpuesto.setEnabled(true);
cbxMoneda.setEnabled(true);
txtPorcentaje.setEditable(true);
txtSimbolo.setEditable(true);
} else {
cbxImpuesto.setEnabled(false);
cbxMoneda.setEnabled(false);
txtPorcentaje.setEditable(false);
txtSimbolo.setEditable(false);
}
}

addListSelectionListener invoke every time there is change in selection

I have Jtable with some rows. If I make selection to some rows, the addListSelectionListener gets invoked each time(for each row selection). Is there any way I can avoid these multiple invoking, as it slows down the process if I select 10000s of rows
Code which shows the selection of the rows
for (int i = 0; i < sArray.length; i++)
{
// int viewindex = mTableForActionListener.getRowSorter().convertRowIndexToView(i);
mTableForActionListener.addRowSelectionInterval(sArray[i].intValue(), sArray[i].intValue());
}
mDocListTable is instance of mTableForActionListener. Code where it gets invoked
mDocListTable.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
handle_TableSelection(e);
}
});
Solution 1:
Remove the listener before your for loop and add it back after for loop.
ListSelectionListener listener = new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
handle_TableSelection(e);
}
};
mDocListTable.getSelectionModel().removeListSelectionListener(listener);
for (int i = 0; i < sArray.length; i++)
{
mTableForActionListener.addRowSelectionInterval(sArray[i].intValue(), sArray[i].intValue());
}
mDocListTable.getSelectionModel().addListSelectionListener(listener);
// add some code here to deal with the new selections in the table.
Solution 2:
In the ListSelectionEvent, check if there's still adjusting taking place.
mDocListTable.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
if(e.getValueIsAdjusting()) return;
handle_TableSelection(e);
}
});

How to deal with multiple jcheckbox and one jbutton JAVA

For example I have 2 checkbox and 1 button my code would be like this.
private class CheckBoxHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (chckbxNewCheckBox1.isSelected() && chckbxNewCheckBox2.isSelected())
{
checkboxcheck1 = 1;
checkboxcheck2 = 1;
}
else if(chckbxNewCheckBox1.isSelected())
{
checkboxcheck1 = 1;
}
else if(chckbxNewCheckBox2.isSelected())
{
checkboxcheck2 = 1;
}
}
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (checkboxcheck1 == 1 && checkboxcheck2 == 1)
{
textFieldSum.setText(String.valueOf(counter));
textFieldSum1.setText(String.valueOf(counter1));
}
else if(checkboxcheck1 == 1)
{
textFieldSum.setText(String.valueOf(counter));
}
else if (checkboxcheck2 == 1)
{
textFieldSum1.setText(String.valueOf(counter1));
}
else
{
checkboxcheck1 = 0;
}
}
}
But then what if I have more than 2 checkbox like 10 or more.It would take forever to to make the if statement in CheckBoxHandler and ButtonHandler. Anybody know how to make it work if I have more than 2 checkbox ?
My program is read the file and count the specific character in the file and then display it. The way to display it is click on the checkbox and click the yes button. But it will take forever for me to do the if statement. You guys have any idea? Thanks yall so much for help.
Declare an array of checkboxes like so
CheckBox[] checkboxes = new CheckBox[10]; // or JCheckBox if using swing
And in the constructor, create them with
String[] filenames = { ... }; // have a list of files?
for(int i=0;i<checkboxes.length;i++){
// for each box, create and add it to your panel
mypanel.add(checkboxes[i]=new CheckBox(filename[i]));
checkboxes[i].addItemListener(mylistener);
}
then in the listener, you can have
public void itemStateChanged(ItemEvent e) {
boolean state = ((CheckBox)e.getSource()).isSelected();
// do something with this state if needed
}
But notice that you don't actually need the item listeners at all.
In the button listener you can do
public void actionPerformed(ActionEvent e) {
for (int i=0;i<checkboxes.length;i++){
if(checkboxes[i].isSelected()){
// do something with file i
}
}
}
Note that if your file operation takes time, you have to do the processing in a new thread, not just in the button handler!

How to check if any button in JPanel is clicked by a user

I've been making a bus booking project and I've made a booking page.
The JPanel named PanelSeat and it contains buttons (about 36 buttons) inside.
I want to check if any button inside JPanel is clicked, then disable the button and finally if a user clicks util 3 buttons, it will be stopped or a user can't click it anymore.
This is the code I've written so far:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I check if button has been clicked?
Since you want to count how many times a button was pressed, and then disable it with counts involved I would suggest that you wrap the Jbutton class in order to make performing those tasks easier, this solution is generally better
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
and this solution is based on your code
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
Add ActionListener to JButton, check example here.

Strange blinking of cell on selection with custom Cell Editor

I am new to working with JTables and having trouble with getting my custom JTable editor to work properly.
I have a number of custom panels with lists and buttons. To renderder them in a cell I am using a custom PanelCellRenderer that has various constructors for each type of the panel.
To make the buttons clickable I have created this simple PanelCellEditor that extends DefaultCellEditor. To access the data stored within cells at the time of editting I pass the reference to the PanelCellRenderer.
The problem I am having is that when I select the cell (by clicking at it), from displaying the list with the button, the cell selected becomes completely blank. When the cell gets deselected the list with data and the button reappear again. Any advice on this will be helpful. Thanks.
public class PanelCellEditor extends DefaultCellEditor {
private PanelCellRenderer pcr;
private Object value;
public PanelCellEditor(final PanelCellRenderer pcr) {
super(new JCheckBox());
this.pcr = pcr;
this.pcr.setOpaque(true);
if (pcr.firstPanel != null) {
pcr.firstPanel.Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
fireEditingStopped();
}
});
pcr.firstPanel.List.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String value = (String) ((javax.swing.JList) e.getSource()).getSelectedValue();
//do something
fireEditingStopped();
}
});
}
else if (pcr.secondPanel != null) {
pcr.secondPanel.Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
fireEditingStopped();
}
});
pcr.secondPanel.List.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
String value = (String) ((javax.swing.JList) e.getSource()).getSelectedValue();
//do something
fireEditingStopped();
}
});
}
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
//// if I comment this whole bit ////
if (isSelected) {
pcr.setForeground(table.getSelectionForeground());
pcr.setBackground(table.getSelectionBackground());
} else {
pcr.setForeground(table.getForeground());
pcr.setBackground(table.getBackground());
}
if (pcr.firstPanel != null)
pcr.firstPanel.list.setListData((String[])value);
else if (pcr.secondPanel != null) {
pcr.secondPanel.list.setListData((String[])value);
}
//////// nothing changes /////////
this.value = value;
return pcr;
}
public Object getCellEditorValue() {
return value;
}
public boolean stopCellEditing() {
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
you could trace the JTable.getTableCellEditor into your objects.
Have you actually registered your editor with the value it should edit with the Jtable?

Categories