What could be the reason why my buttons are not responding to the ActionListener?

I am encountering some difficulties in making things happen when I click a button.

  1. This is where the buttons are declared:

    public class DoND extends JFrame implements ActionListener {
    
    public JButton btnsuit1, btnsuit2, ... , btnsuit26;
    
    public static void main(String[] args) {
    
        new DoND();
    }
    
  2. Here is detailed information about two of the buttons (there are a total of 26).

    JButton btnsuit1 = new JButton();
    btnsuit1.setIcon(new ImageIcon("images\\suitcases\\case1.png"));
    btnsuit1.setPreferredSize(new Dimension(200, 150));
    btnsuit1.setHorizontalAlignment(SwingConstants.CENTER);
    btnsuit1.addActionListener(this);
    
    JButton btnsuit2 = new JButton();
    btnsuit2.setIcon(new ImageIcon("images\\suitcases\\case2.png"));
    btnsuit2.setPreferredSize(new Dimension(200, 150));
    btnsuit2.setHorizontalAlignment(SwingConstants.CENTER);
    btnsuit2.addActionListener(this);
    
  3. This is where the buttons are added to the center panel, which is then added to the main panel, and finally to the frame.

Center Panel

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    centerPanel.setBackground(Color.BLACK);
    centerPanel.add(btnsuit1);
    centerPanel.add(btnsuit2);

Main Panel

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.setBackground(Color.BLACK);
    mainPanel.add(northPanel, BorderLayout.NORTH);
    mainPanel.add(centerPanel, BorderLayout.CENTER);
    mainPanel.add(eastPanel, BorderLayout.EAST);
    mainPanel.add(westPanel, BorderLayout.WEST);
    mainPanel.add(southPanel, BorderLayout.SOUTH);

Frame

    setContentPane(mainPanel);
    setSize(3000, 1000);
    setTitle("Deal or No Deal");
    setLocationRelativeTo(null);
    setResizable(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  1. And here is the action listener:

    public void actionPerformed(ActionEvent e) {
    
    if (e.getSource() == btnsuit1)
    {
        btnsuit1.setVisible(false);
    }
    
     if (e.getSource() == btnsuit2)
    {
        btnsuit2.setVisible(false);
    }
    

I am unsure why nothing is happening, but there are a few possibilities that I have considered:

a) The buttons with ActionListener may differ from what ActionPerformed is looking for.

b) I might need to extend ActionListener to the secondary panel where all my buttons reside.

Your help is greatly appreciated.

--

Grant

Answer №1

Your JButtons were declared as class fields, but they were never initialized. Instead of initializing them, you created a new JButton like this:

JButton btnsuit1 = new JButton();

Therefore, the btnsuit1 in btnsuit1.setVisible(false) is likely null. To fix this issue, try changing the initialization of btnsuit1 to:

btnsuit1 = new JButton();

This adjustment should make it work properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The text consistently remains positioned to the right of my image

Photo Gallery Title Issue I'm working on a photo gallery project where I want to add titles underneath each image. However, I'm facing a problem where the title is appearing next to the image instead of below it. You can see the issue in this sc ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...

Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly ...

How to center elements vertically in a navbar using Bootstrap 5

I am currently utilizing bootstrap to design a navbar featuring various links. One of these links is a button, which is causing alignment issues with the rest of the links. body{ background: rgb(27, 25, 25); } .btn{ border-radius: 3em; } ...

Developing an Android Bluetooth application that can support various API levels within a single APK

My App originally used the Bluetooth function on Jelly Bean (Android 4.3), but when I tried running it on Lollipop, it failed due to differences in the Bluetooth class methods between the two versions. To address this issue, I learned that I could add cod ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

The background image on my link bar is inexplicably not appearing

I've been trying to solve this issue for hours and I'm at a loss. Initially, the background image was displaying correctly, but now it's not working. HTML: <head> <link type="text/css" rel="stylesheet" href="css/normalize.css" ...

Having issues with ToggleClass and RemoveClass functionalities not functioning properly

As a novice in Jquery and CSS/scss, I've managed to create dynamic bootstrap cards for recording players. Each card consists of a music-container with control-play and vinyl elements. I aim to have multiple bootstrap cards generated based on the data ...

Tips for keeping div and input tags selected even after a user clicks

I am working on a quiz script and I am trying to customize it so that when a user clicks on the div or input tags, they remain selected with a different background color. Currently, I have achieved changing the background color of the div when clicked, ...

Firebase hosting adjusts the transparency of an element to 1% whenever it detects the presence of CSS opacity

I'm currently working on a website using Vue.js and Firebase. Everything runs smoothly locally, including a button with a desired low opacity. However, when I deploy the site to Firebase Hosting, the button's opacity inexplicably changes to 1% an ...

Tips for minimizing padding and margin in a Bootstrap template

I recently downloaded the page from "https://getbootstrap.com/docs/5.3/examples/heroes/", and I've removed all sections in index.html except for the "hero" section and the "sign-up form". However, there is too much white space between these two elemen ...

"Resolving an inconsistency problem with the Vary header in Htaccess

Could someone help me identify the issues in my htaccess code? I'm encountering errors: This response is negotiated, but doesn't have an appropriate Vary header. The resource doesn't send Vary consistently. ## add vary header <IfModule ...

Discovering distinct colors for this loading dots script

Looking for assistance with a 10 loading dots animation script. I'm trying to customize the color of each dot individually, but when I create separate divs for each dot and control their colors in CSS, it causes issues with the animation. If anyone ...

Troubleshooting Stale Element Issue in Java and Selenium

While using Selenium, I keep facing the Stale Element Error. As per my research, this error occurs when you switch away from a page or when an element on the page has been modified. The problem arises while I'm traversing through a list of web element ...

Implementing mock methods with JUnit and Mockito

I have been attempting to test the following class: public class PreprocessorServiceImpl implements PreprocessorService { private static final Logger LOG = LoggerFactory.getLogger( PreprocessorServiceImpl.class ); private FileServiceProvider fileService ...

tips for reducing the size of the recaptcha image to display just one word

The custom recaptcha theme I'm working with requires the image to be smaller in width but not in height. Is there a way to achieve this requested design? ...

What should I designate as the selector when customizing dialog boxes?

I am attempting to change the title bar color of a dialog box in CSS, but I am running into issues. Below is the HTML code for the dialog box and the corresponding CSS. <div id="picture1Dialog" title = "Title"> <p id="picture1Text"> ...

Text overlay on Material UI Card

I am currently using the Material UI Card and CardMedia components in my application, but I am having trouble with overlaying text on top of the image. Below is a simplified version of what I have been attempting: <Card> <CardMedia image={this. ...

What is the best way to set up our class when the storm topology is being initialized?

Can someone please help me with how to successfully call the init method of a custom class when starting the storm topology, ensuring that it only runs once? ...