1
votes

I have this strange problem when I add buttons to the toolbar. I added action listener to one button added before the frame is shown and it works fine:

btn.addActionListener(new ActionListener() {
    @Override
     public void actionPerformed(ActionEvent e) {
        toolbar.add(new JButton("new button"));
     }
});

I also added a piece of code that is supposed to add a new button after some plugins are loaded, and for some reason that piece of code does not work.

@Override
public void handle() {
    System.out.println("Button added");
    MainFrame frame = Application.getInstance().getMainFrame();
    frame.getToolbar().add(new JButton("Plugin button"));

    frame.getToolbar().revalidate();
    frame.getToolbar().repaint();

    System.out.println(frame.getToolbar().getComponents().length); // It is definitely being added, just not shown

}

The button is definitely being added, just not shown. I would really appreciate any help since this thing is blocking me from progressing any further.

1
Your best bet here is to show us compilable and runnable code. Understand that we're not asking you to show your whole program, but rather to condense your question/problem into a single small class that is compilable by any and all of us, and demonstrates your problem. In other words, a minimal reproducible example (please read the link). Also understand that this is not a link to code, but rather pertinent code that you post here with your question as an edit. - Hovercraft Full Of Eels
The button is definitely being added, just not shown. - then you have two frames in your application. One that is visible on the screen and another one that is just sitting in memory. This usually happens when your class extends JFrame and then you create a second JFrame. Don't extend JFrame and you won't have this confusion! - camickr
@camickr You are right, I did actually instantiate main frame twice. I made a mistake of calling Application constructor instead of getInstance() in main (main is inside of application so I was able to call the constructor even though it it private), so when I called getInstance the first time, main frame was instantiated again. Thanks for all your help. - user1176999

1 Answers

0
votes

I found out what the problem was. The problem was that I instantiated MainFrame twice, first by calling Application constructor in main and then when calling Application.getInstance(), so all components added to the MainFrame were removed.