簡體   English   中英

退出按鈕的退出功能

[英]Exit function for exit button

如何在“ EXIT LAHH”中實現退出功能! 單擊后單擊按鈕? 我不確定要使用什么代碼。 我嘗試了addActionListener,但不確定是否需要添加到()中。

import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestButton1 {
private Frame F;
private Button B;
private Button C;

public TestButton1(){
F = new Frame("Welcome!");
B = new Button("Press Me! \nSo that, you can genarate OUTPUT result at the CONSOLE");
B.setActionCommand("ButtonPressed");
C = new Button("EXIT LAHHH!");
C.setActionCommand("ButtonPressed");

//javax.swing.WindowConstants.EXIT_ON_CLOSE }

public void launchFrame(){
B.addActionListener(new mainclass());   

//Allow user to use the (X) close button
F.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we){
            System.exit(0);
      }
    });


F.setLayout(new FlowLayout());
F.add(B);
F.add(C);


F.setBackground(Color.green);
B.setBackground(Color.pink);
C.setBackground(Color.white);
F.setSize(600, 70);
F.setVisible(true);     
}    
public static void main(String[] args) {
    TestButton1 guiApp = new TestButton1();
    guiApp.launchFrame();
}  }
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

C.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent evt)
    {
        System.exit(0);
    }
});

您要關閉相框嗎? 這是教程

嘗試: frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

首先,在哪里看不到“您的退出函數”,因此我假設您的意思是System.exit(0); 通過那個。

我看到您已經在此處實現了WindowListener:

F.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent we){
        System.exit(0);
  }
});

它實質上添加了一個匿名內部類作為偵聽器。 使用相同的概念,我們可以將ActionListener添加到按鈕。

考慮以下:

C.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        System.exit(0);
    }
});

當按下並釋放按鈕時, ActionListener執行,並在actionPerformed()方法中執行代碼。

此外,您還可以替換System.exit(0); 在帶有setVisible(false);的“按鈕退出代碼”中setVisible(false);

像這樣:

C.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        setVisible(false);
    }
});

我認為這是一個更優雅的解決方案,在結束程序之前關閉框架。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM