1

This class represents the button panel of a UI I have created, the second JButton named 'btnNext' doesn't display text however the first JButton does, why is this?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;

public class ButtonPanel extends JPanel {
    private MainPanel mainPanel;

    // Buttons
    private JButton btnRunTheAlgorithm = new JButton("Run the Algorithm");
    public static JButton btnNext = new JButton("Next Step");

    public ButtonPanel(MainPanel mainPanel) {
        this.mainPanel = mainPanel;
        this.setLayout(new FlowLayout());
        this.add(btnRunTheAlgorithm);
        this.add(btnNext);


        this.btnRunTheAlgorithm.addActionListener(e -> {
            Algorithm main = new Algorithm(mainPanel);
            main.Run();
        });

        this.btnNext.setAction(new AbstractAction() {
            public void actionPerformed(ActionEvent ae) {
                synchronized (btnNext) {
                    btnNext.notify();
                }
             }
         });
     }
 }

The buttons displays to the panel as on the image below:

Buttons:

https://i.stack.imgur.com/qsz9D.png

I'm also not sure the AbstractAction works, so I suppose that could be the cause of the text not displaying but I have no idea why if that is the case.

camickr
  • 321,443
  • 19
  • 166
  • 288
Emily
  • 21
  • 4
  • Does btnNext need to be "public static"? – Neil P. Mar 02 '18 at 20:13
  • 3
    https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html. Your action has no text, and the text of the action is used as the text of the button, so... (BTW, your listener makes no sense, and it should definitely not be static) – JB Nizet Mar 02 '18 at 20:15
  • @Neil Yes I think so, because I'm referencing it in another class in a static context. – Emily Mar 02 '18 at 20:16
  • `I'm also not sure the AbstractAction works` Did you add a System.out.println(...) statement to the listener to see if the code is executed? This is basic debugging. Why does one button use an `ActionListener` and the other an `Action`? Be consistent with your code. Seems to me like you have no idea what you are doing and are just copying random pieces of code from some example. Read the Swing tutorial for the basics. Also, there is no need for the "synchronized" code in the listener – camickr Mar 02 '18 at 20:26
  • @JBNizet Thanks, I added the text and now there's text on the button. What do you mean by the listener should be static? – Emily Mar 02 '18 at 20:30
  • 1
    the button should definitely **not** be static. Each instance of ButtonPanel should have its own btnNext, not shared with other instances. – JB Nizet Mar 02 '18 at 20:33
  • @Emily *"Yes I think so, because I'm referencing it in another class in a static context"* - That's not how 'static` should be used – MadProgrammer Mar 02 '18 at 20:44

0 Answers0