简体   繁体   English

如何从其他类java swing调用JButton

[英]How to call JButton from other class java swing

I have a GUI class which contains a JButton: 我有一个包含JButton的GUI类:

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) . 在其他类中,我将处理一些事情,当完成该过程后,我想禁用GUI类中的按钮,例如: GUI.sub.setEnabled(false) How can I do that? 我怎样才能做到这一点?

Thank you in advanced! 谢谢高级!

In your other class event, you call Frame.getFrames() that returns an array of all frames. 在另一个类事件中,调用Frame.getFrames()返回所有框架的数组。 Then you get your GUI frame and call GUI.sub.setEnabled(false) 然后,您获取GUI框架并调用GUI.sub.setEnabled(false)

You should put a getter method for your JButton in the Gui class, Like this: 您应该在Gui类中为JButton放置一个getter方法,如下所示:

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

and to disable the Button from another class you do this: 并从另一个类禁用按钮,请执行以下操作:

Gui.getsubButton().setEnabled(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM