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

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

Related

Minesweeper Object GUI

I am trying to do a simple Minesweeper game using JFrame, however I am having troubles with the creation of objects. I am creating 96 buttons, some of which get the property of being wrong ("F") and right ("R"):
public class GUIBase extends JFrame {
private JButton button;
private JButton fButton;
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
//Fields
int position;
for (int i = 0; i < 96; i++) {
position = (int) (Math.random() * 100);
if (position < 80) {
button = new JButton("R");
button.setToolTipText("Is this the correct one?");
add(button);
} else {
fButton = new JButton("F");
fButton.setToolTipText("Is this the correct one?");
add(fButton);
}
}
I then use ActionListener in order to check whether or not the button is correct. If the button is correct, it will get .setEnabled(false), otherwise the game ends:
//Action
Action action = new Action();
button.addActionListener(action);
fButton.addActionListener(action);
}
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() == button) {
button.setEnabled(false);
} else if (event.getSource() == fButton) {
JOptionPane.showMessageDialog(null, "You lost!");
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "An error ocurred");
System.exit(0);
}
}
}
Everything in the game turns out as planned, however only the last correct button ("R") and last wrong one ("F") are connected to the ActionListener. The rest of the buttons do not do anything when pressed.
How can I fix this?
The problem is that you only have two variables (attributes of the class GUIBase, specifically), and your are assigning to it each time you create a new button. Hence, you only have a reference to the last buttons.
You need an array of buttons. Let's see:
public class GUIBase extends JFrame {
public final int MAX_BUTTONS = 96;
private JButton[] buttons;
// ...
}
The next step is to create the array itself at the beginning:
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
this.buttons = new JButton[MAX_BUTTONS];
//Fields
int position;
for (int i = 0; i < buttons.length; i++) {
position = (int) (Math.random() * 100);
this.buttons[ i ] = new JButton("R");
this.buttons[ i ].setToolTipText("Is this the correct one?");
this.add(this.buttons[ i ]);
Action action = new Action();
this.buttons[ i ].addActionListener(action);
}
}
You'll probably need more depth in arrays in order to completely understand the code. Basically, an array is a continuous collection of variables, which you can index by its position, from 0 to n-1, being n the number of positions.
Then you'll probably be able to fill the gaps yourself.
Hope this helps.
One part of your problems is coming from your action listener.
Of course, one part is that your code probably needs a list/array to keep track of all created buttons; but at least right now, you can rework your code without using arrays/list:
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() instanceofJButton) {
JBUtton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("R") ...
else if (buttonText.equals("F")
You see, the whole point here is: as of now, you just need to know what kind of button was created. And your ActionListener knows which button it was clicked on ...

Returning JButton's to Enabled via separate ActionListener

I've implemented code that will - amongst other things - make a series of JButton's disabled after being clicked. The code for this is below:
ActionListener disableButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append(event.getActionCommand());
wordDisplay.setText(theModel.getCurrentWord());
((JButton) event.getSource()).setEnabled(false);
}
};
theModel.randomLetters();
for (int i = 0; i < 16; i++) {
dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
Notice the "((JButton)event.getSource()).setEnabled(false);" line. This, after completing the previous lines, makes any clicks on the button inactionable. I wish to reverse this when a seperate button is clicked. It's code is below:
JButton submitWordButton = new JButton("Submit Word");
submitWordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent submit) {
wordDisplay.setText("");
theModel.currentWord.delete(0, 16);
((JButton) submit.getSource()).setEnabled(true);
}
});
info.add(submitWordButton, BorderLayout.SOUTH);
My dilemma is I don't know how to reference the JButton's outside of the ActionListener that disables them once clicked and hence enabled them again. The button I want to use to do this (the one with code most recently pasted above) is in another class. Any ideas?

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.

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

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

JButton Not performing Any Action

Hi I have a JButton defined like:
private JButton btnExp;
private JPanel jpShow = new JPanel();
jpShow.setLayout(null);
btnExp = new JButton("Export");
btnExp.setBounds(100, 250, 120, 25);
jpShow.add(jspTable);
jpShow.add(btnExp);
//Adding Panel to Window.
getContentPane().add(jpShow);
public void actionPerformed(ActionEvent ae) {
try{
Object obj = ae.getSource();
if (obj == btnExp) {
FileWriter excel = new FileWriter("File.TSV");
for(int i = 0; i < dtmCustomer.getColumnCount(); i++){
excel.write(dtmCustomer.getColumnName(i) + "\t");
}
excel.write("\n");
for(int i=0; i< dtmCustomer.getRowCount(); i++) {
for(int j=0; j < dtmCustomer.getColumnCount(); j++) {
excel.write(dtmCustomer.getValueAt(i,j).toString()+"\t");
}
excel.write("\n");
}
excel.close();
JOptionPane.showMessageDialog(this, "File Written","Success", JOptionPane.PLAIN_MESSAGE);
}
}catch(Exception e){
System.out.println(e);
}
}
Am trying to get the JTable to be exported after the user clicks the button but nothing happens and no exception is raised. Am I doing it the wrong way?
You are not adding the ActionListener to your button correctly. The correct way is:
btnExp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add here the contents in your actionPerformed method
}
})
The code you post will not even compile
You should add the ActionListener to your JButton as #Dan already showed in his answer
You should make sure you close the FileWriter in a finally block. Now, when an exception occurs it will not be closed
You will end up with a non-responsive UI if you export the table on the Event Dispatch Thread. Consider using a SwingWorker. Consult the Concurrency in Swing tutorial for more information
Avoid the use of setLayout( null ) and setBounds. Use a decent LayoutManager instead

Categories