Why does this method get called twice when button is clicked? - java

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());
}
}

Related

JComboBox triggering null pointer even though it was not called on?

working on a school project. My program has an action listener for a jcombobox that once i hit submit, clears the box and hides it. Thats when it says null pointer, even though I'm not using it or clicking it after I clear it. Also, it only happens the first time I clear it.
JComboBox sidComboBox = new JComboBox();
sidComboBox.setFont(new Font("Lantinghei TC", Font.PLAIN, 15));
sidComboBox.setBounds(139, 127, 222, 27);
contentPane.add(sidComboBox);
btnSubmit.addActionListener (new ActionListener () //adding action listener to the button component and creating a specific action performed method (override) for the button
{
public void actionPerformed (ActionEvent e)
{
if (btnSelect == 5)
{
sidComboBox.setEnabled(false);
sidComboBox.setVisible(false);
fnComboBox.setEnabled(false);
lnComboBox.setEnabled(false);
pnComboBox.setEnabled(false);
fnComboBox.setVisible(false);
lnComboBox.setVisible(false);
pnComboBox.setVisible(false);
}
btnAdd.setEnabled(true);
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
btnSearch.setEnabled(true);
btnViewAll.setEnabled(true);
TAFirstName.setVisible(false);
TALastName.setVisible(false);
TAStudentID.setVisible(false);
TAPhoneNumber.setVisible(false);
lblFirstName.setVisible(false);
lblLastName.setVisible(false);
lblPhoneNumber.setVisible(false);
lblStudentId.setVisible(false);
btnSubmit.setVisible(false);
btnSubmit.setEnabled(false);
btnEditor.setVisible(false);
btnEditor.setEnabled(false);
TAFirstName.setEditable(false);
TALastName.setEditable(false);
TAStudentID.setEditable(false);
TAPhoneNumber.setEditable(false);
TAFirstName.setText(null);
TALastName.setText(null);
TAStudentID.setText(null);
TAPhoneNumber.setText(null);
sidComboBox.setVisible(false);
sidComboBox.setEnabled(false);
sidComboBox.removeAllItems();
fnComboBox.setVisible(false);
fnComboBox.setEnabled(false);
fnComboBox.removeAllItems();
lnComboBox.setVisible(false);
lnComboBox.setEnabled(false);
lnComboBox.removeAllItems();
pnComboBox.setVisible(false);
pnComboBox.setEnabled(false);
pnComboBox.removeAllItems();
btnSelect = 0;
}
}
);
sidComboBox.addActionListener (new ActionListener () //adding action listener to the button component and creating a specific action performed method (override) for the button
{
public void actionPerformed (ActionEvent e)
{
int check = db.getNum() - 1;
if (check == -1) {
}
else {
int studentID = (int) sidComboBox.getSelectedItem();
int num = db.getNum();
for (int b1 = 0; b1 < num; b1++)
{
int nom = (db.studentList[b1].getStudentID());
if (studentID == nom)
{
fnComboBox.setSelectedItem((db.studentList[b1]).getFirstName());
lnComboBox.setSelectedItem((db.studentList[b1]).getLastName());
pnComboBox.setSelectedItem((db.studentList[b1]).getPhoneNumber());
break;
}
}
}
}
}
);
The error happens at this line specifically, not when I use it but when I hit the submit button.
int studentID = (int) sidComboBox.getSelectedItem();
I know its null, but I'm not calling on the box when its null. So why is it telling me its null??
The problem is you call sidComboBox.removeAllItems(); in your submit-method. This changes the selection and therefore fires an ActionEvent as stated in the tutorial here.
Ways to circumvent this are presented here

One program, different on multiple computers

First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});

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.

Get the value when JButton increments value in JLabel and put into database

I have this code right here, which is a label with a button, and when the button is clicked the label incrememnts by one:
int helpfulNumber = content.getHelpful();
JButton helpfulBT = new JButton("Helpful");
reviewBoxPanel.add(helpfulBT);
JLabel helpfulLB = new JLabel("Helpful: " + helpfulNumber);
reviewBoxPanel.add(helpfulLB);
helpfulBT.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{
int helpfulNumber = content.getHelpful();
int newHelp = helpfulNumber + 1;
helpfulLB.setText("Helpful:" + newHelp);
}
});
helpfulLB.setText("Helpful: " + newHelp); // this doesn't work
In the code below, when submit is clicked, I need to get the value of the label but with the new value of helpfulNumber. As it is now, it only seems to get the old value of the label
final JButton submitBT = new JButton("Submit");
southPanel.add(submitBT);
submitBT.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == submitBT)
{
MovieReview some = new MovieReview();
some.setUser(userTF.getText());
some.setMovie(titleTF.getText());
some.setFeatured(featuredCB.isSelected());
some.setRating(Integer.parseInt(ratingTF.getText()));
some.setHelpful(helpfulNumber);
some.setUnhelpful(notHelpfulNumber);
some.setComments(reviewTA.getText());
some.setId(content.getId());
if(owner.updateReview(isUpdate, some))
{
// success
try {
MovieReviewDSC.edit(some);
//tableModel.fireTableRowsInserted(firstRow, lastRow);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JOptionPane.showMessageDialog(ReviewEditor.this, "Database succesfully updated!");
}
else
{
// fail
}
}
}
});
So the idea is that when this frame is open, there are already values in there from content that may not be 0. Currently if I click the button to increment and click submit, the number remains at its original value.
I've tried using the helpfulLB.setText("Helpful: " + newHelp); again outside the helpfulBT actionListener but the newHelp variable isn't recognized. Any help would be appreciated, thank you for your time.
Solution thanks to #tiago7 and #Boosha
helpfulNumber = content.getHelpful();
JButton helpfulBT = new JButton("Helpful");
reviewBoxPanel.add(helpfulBT);
JLabel helpfulLB = new JLabel("Helpful: " + helpfulNumber);
reviewBoxPanel.add(helpfulLB);
helpfulBT.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{
helpfulNumber += 1;
helpfulLB.setText("Helpful:" + helpfulNumber);
}
});
while declaring int helpfulNumber in the frame. Thanks guys, I appreciate the help
Seems that you trying to submit something similar to 'Like' action in social network.
Just declare the variable in your frame, that will hold your 'helpful' value.
Initialize in, when you load the data, increment it in button ActionListener and read it in submit action.
You just need to provide a global scope for this variable, so it can be accessed from all your listeners.
Declare newHelp outside the listener and use it inside the listener by removing the int declaration.

Categories