javapaneljtogglebutton

Creating and adding JToggleButton to a panel programmatically


I'm developing a software where a user has to setup the software according to the users' need before using it.

When the user clicks on a menu item the software throws a JDialog and asks for a user input and the software stores the input. This works fine. I've got a problem in the next bit. I want a toggle button (with the text entered by the user as its label) inside a panel. I tried using categoryPanel.add(C.getCategoryButton) but it didn't work. please help! Thanks in advance.

Here is what I've done... I've created a Category class that extends JToggleButton

public class Category extends JToggleButton implements ActionListener
{
    private JToggleButton categoryButton;


    public JToggleButton getCategoryButton()
    {
        buildCategoryButton();
        return categoryButton;
    }

    private void buildCategoryButton()
    {
        categoryButton = new JToggleButton();
        categoryButton.setText(MainFrame.getUserInput());
        categoryButton.setVisible(true);
    }

This is where the getCategoryButton() method is invoked

private void catCapBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        userInput = catCapTextField.getText(); //works fine
        Category C = new Category();
        categoryPanel.add(C.getCategoryButton()); //doesn't work
        validate();

        catCapture.setVisible(false);//this closes the JDialog, and it works fine.
    } 

Solution

  • When you extend JToggleButton, the Category class you have created becomes an instance of JToggleButton. Therefore, you don't need a private instance of JToggleButton. I suggest something like the following:

    public class Category extends JToggleButton implements ActionListener {
    
        public Category() {
            super(MainFrame.getUserInput());
        }
    

    Also, if I'm not mistaken, buttons do not need to be set as visible.