Ock
Ock

Reputation: 1330

How to call JButton from other class java swing

I have a GUI class which contains a JButton:

public class GUI {

   static JFrame mainFrame;
   static JLabel headerLabel;
   static JLabel statusLabel;
   static JPanel controlPanel;
   static JButton sub;



   public GUI(){
      prepareGUI();

   }


   public static void prepareGUI(){
      mainFrame = new JFrame("Service 2 - Evaluate Sensor Values");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    



      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);

      sub = new JButton("Send Subscribe to Service 1");

      showButtonDemo();

      mainFrame.setVisible(true);  
   }



   public static void showButtonDemo(){

      headerLabel.setText("Configuration Phase"); 

      headerLabel.setFont(new Font("Serif", Font.PLAIN, 14));

      sub.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             Monitor.createWaterSubscriptionResources();
             Monitor.createTemperatureSubscriptionResources();
         }          
      });


      controlPanel.add(sub);


      mainFrame.setVisible(true);  
   }
}

In other class, I will process something, and when the process done, I would like to disable the button in the GUI class, something like:GUI.sub.setEnabled(false). How can I do that?

Thank you in advanced!

Upvotes: 0

Views: 923

Answers (2)

Gherbi Hicham
Gherbi Hicham

Reputation: 2584

You should put a getter method for your JButton in the Gui class, Like this:

public static JButton getSubButton(){
     return this.sub;
}

and to disable the Button from another class you do this:

Gui.getsubButton().setEnabled(false);

Upvotes: 0

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

In your other class event, you call Frame.getFrames() that returns an array of all frames. Then you get your GUI frame and call GUI.sub.setEnabled(false)

Upvotes: 1

Related Questions