William Falcon
William Falcon

Reputation: 9823

JTextArea swallowing JButton action listener Java

I have an action listener on a JButton and a JTextArea in the button. However when I click the button the text area swallows the event, and nothing happens to the button.

How can I click through the area?

Thank you

Button code

public class CustomFoodItemButton extends JButton{


    public JTextArea buttonTitle;
    /**
     * Public constructor
     * @param title
     */
    public CustomFoodItemButton(String title) {

        //Set button text by using a text area
        buttonTitle = new JTextArea();
        buttonTitle.setText(title);
        buttonTitle.setFont(new Font("Helvetica Neue", Font.PLAIN, 15));

        buttonTitle.setEditable(false);
        buttonTitle.setWrapStyleWord(true);
        buttonTitle.setLineWrap(true);
        buttonTitle.setForeground(Color.white);
        buttonTitle.setOpaque(false);


        //Add the text to the center of the button
        this.setLayout(new BorderLayout());
        this.add(buttonTitle,BorderLayout.CENTER);

        //Set the name to be the title (to track actions easier)
        this.setName(title);

        //Clear button so as to show image only
        this.setOpaque(false);
        this.setContentAreaFilled(false);
        this.setBorderPainted(false);

        //Set not selected
        this.setSelected(false);

        //Set image
        setImage();
    }

GUI Class code

private void addFoodItemButtons (JPanel panel){

        //Iterate over menu items
        for (FoodItem item : menuItems) {

            //Create a new button based on the item in the array. Set the title to the food name
            CustomFoodItemButton button = new CustomFoodItemButton(item.foodName);

            //Add action listener
            button.addActionListener(this);


        }
    }

Upvotes: 0

Views: 504

Answers (1)

RaptorDotCpp
RaptorDotCpp

Reputation: 1475

EDIT For multiline JComponents, check out this answer: https://stackoverflow.com/a/5767825/2221461

It seems to me as if you're overcomplicating things. Why are you using a TextArea on a button if you can't edit the TextArea's text?

There is another constructor for JButtons:

JButton button = new JButton(item.foodname);

This will create a button with the value of 'item.foodname' as text.

You could then simplify your constructor:

public class CustomFoodItemButton extends JButton {
    public CustomFoodItemButton(String title) {
        super(title);
        setName(title);
        setOpaque(false);
        setContentAreaFilled(false);
        setBorderPainted(false);
        setSelected(false);
        setImage();
    }
}

Please let me know if I misinterpreted your question.

Upvotes: 1

Related Questions