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!
Related
I've been trying to make a listener (I'm not really sure whether I should be using an ItemListener or ActionListener) respond to changes in a JComboBox by changing a JLabel image next to the box.
I tried defining the actionPerformed method in the constructor of the class under the addActionListener call on the combo box, as well as outside the constructor, and the actionPerformed never seems to execute. I've added a println to each one to test whether the method is actually working when I select an item in the box, but neither one appears to output anything, leading me to believe the actionPerformed method is not executing for some reason. A lot of different answers elsewhere have defined actionListeners and actionPerformed in multiple different places, such as a separate class or in an instance variable declaration.
public class MainBattle
{
//instance variables
public MainBattle() throws FileNotFoundException,IOException
{
//creation of ArrayLists used later
for(JComboBox<String> j : party1)
{
j.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Listener active");
if(e.getSource() instanceof JComboBox)
{
JComboBox<String> cb = (JComboBox<String>)e.getSource();
String content = (String)cb.getSelectedItem();
if(party1.indexOf(cb) != -1)
{
party1Image.get(party1.indexOf(cb)).setIcon(new ImageIcon(".\\res\\sprites_small\\"
+ content.substring(0,content.indexOf(" ")) + ".png"));
}
}
selectFrame.revalidate();
selectFrame.repaint();
}
});
}
createUI();
}
public void createUI()
{
//building GUI elements and displaying
for(int i = 0; i < 6; i++)
{
party1.add(new JComboBox<String>());
party2.add(new JComboBox<String>());
}
for(int i = 0; i < 6; i++)
{
party1Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
party2Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
}
//building GUI elements and displaying
}
// Commented out to make sure existence of multiple methods is not problematic
/*
public void actionPerformed(ActionEvent e)
{
System.out.println("Action");
}
*/
public static void main(String[] args) throws IOException
{
new MainBattle();
}
}
I am trying to make it easier to make buttons by making a method, but when i use the method to make a button nothing happens when i press the button, even though i have a listener for the button
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
i use assignButton(Check,"words"); to make the button
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else
{
code = 2;
}
repaint();
every time i press the button it sets code to 2, anyone know what i am doing wrong?
Edit:
full code
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PressSafeTemp extends Applet implements ActionListener
{
Button clear,Check;
int code = 0;
public void init() //assigns buttons
{
clear = new Button("C");
add(clear);
clear.addActionListener(this);
assignButton(Check,"words");
}
public void paint(Graphics g)
{
g.drawString(""+code,10,10);
}
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else if(event.getSource() == clear)
{
code = 0;
}
else
{
code = 2;
}
repaint();
}
}
The problem is you pass Check to the method (as wtf) but then immediately set it to a new instance; this instance is not Check. It does get added but you can't get at it with Check.
You probably want to do...
Button getButton(String text) {
Button button = new Button(text);
button.addActionListener(this);
return button;
}
and then Check = getButton(someText); followed by add(Check);.
If you don't actually need Check laying around, you could also just add it directly with add(getButton(someText));.
I'm not sure what means for you event.getSource() == Check but that is the key, you need to check the correct comparison in your case. Something like for example:
event.getSource().class.equals(JCheckBox.class)
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.
I am building a simple applet and in my applet I have a combo box with a drop down list. When an option is selected, and a button "add" is clicked, the selection is take and pass to a method that creates an object. The only problem is that when I click the button, it adds the object fine, but then when I try adding another slelection, it deletes the previous one and sets the new one equal to the same attributes as the new one. So in essence it is re adding the selection.
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTooObj(comboBox.getSelectedItem().toString(), lblStatusLabel);
System.out.println(comboBox.getSelectedIndex());
}
});
private void addToobj(String num,JLabel j){
System.out.println(num);
Object objToBeAdded = null;
long objNumber = Long.parseLong(num);
int quan = 0;
if (objNumber == 12354589621l) {
objToBeAdded = new Item(objNumber, 2.00, quan);
} else if (objNumber == 21) {
objToBeAdded = new Item(objNumber, 1.50, quan);
} else if (objNumber == 12) {
objToBeAdded = new Item(objNumber, 5.20, quan);
} else {
System.out.println("error");
}
oldObj.add(objToBeAdded);
}
Within your actionPerformed method, you could get the action command and review what actions it is been fired for and then only call your method if the action is the action you want.
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
System.out.println("The action was: " + action);
if(action.equals("What ever action you want")){
addTooObj(comboBox.getSelectedItem().toString(), lblStatusLabel);
System.out.println(comboBox.getSelectedIndex());
}
}
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