简体   繁体   English

如何实现Jbutton和事件监听器以关闭应用程序?

[英]How do i implement a Jbutton and event listener to close the application?

The following is my code...the jButton would be added in the GuI method. 以下是我的代码... jButton将添加到GuI方法中。 I need a jbutton to add to the container and an eventlistener to enable the application to close when pushed. 我需要一个jbutton来添加到容器中,并需要一个事件侦听器来使应用程序在按下时关闭。

public class BeetsWk1 extends JFrame{

public BeetsWk1(){

     GuI();
}

public void GuI(){
      FlowLayout layout = new FlowLayout();

        layout.setAlignment(FlowLayout.CENTER);

    Container container;
    container = getContentPane();
    container.setBackground(new Color(052,062,138));
    container.setLayout(layout);

    JLabel label = new JLabel();
    label.setText ("Hello World" );
    label.setSize( 500, 400);
            label.setFont( new Font( "SanSerif", Font.PLAIN, 15) );
            label.setHorizontalAlignment( JLabel.CENTER );
    label.setForeground(Color.white);
    container.add( label );
}

    public static void main(String[] args) {
        // TODO code application logic here
            Dimension dimension = new Dimension(500, 500);
                        BeetsWk1 window = new BeetsWk1();
                       window.setVisible(true);
                        window.setSize(dimension);
                           window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
    }

    private Dimension Dimension(int i, int j) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

What's stopping you? 什么事拦住你了?

JButton button = new JButton();
button.setText("Some text");
getContentPane().add(button);

button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent evt) {
           System.exit(0);
      }
});
// 'this' represents the frame
// the 'button' is provided free
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

If you want to close your container then 如果您想关闭容器

button.addActionListener(new ActionListener() {
       @Override 
      public void actionPerformed(ActionEvent evt) {
          jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//jframe is your JFrame Object
      }
});

or if you want to close the total application then 或者,如果您想关闭整个应用程序,则

system.exit(0);

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

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