如何计算用户在Java程序中单击X按钮的次数?

k7fdbhmy  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(170)

我在eclipse中创建了一个UI。我该如何让它计算用户点击X按钮的次数?我试过使用WindowListeners和ActionListeners,但我不能让它们工作,我可能用错了。

import java.awt.Font;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class NewWindowTest {

    JFrame frame = new JFrame();
    JLabel label = new JLabel("Hello!");
    
    
    public void windowAction(WindowEvent e) {

        //How do I make it count how many times the user clicks on the X to close the window?
        
        int numClicks = 0;
        numClicks++;
        
        if (numClicks>10); {
            displayMessage("Just stop."); }
}
    private void displayMessage(String string) {

    }
    NewWindowTest(){
        
        label.setBounds(0,0,100,50);
        label.setFont(new Font(null,Font.PLAIN,25));
        
        frame.add(label);
        
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setSize(420,420);
        frame.setLayout(null);
        frame.setVisible(true); 
    } 
}
nbnkbykc

nbnkbykc1#

尝试将事件侦听器添加到JFrame对象:

...
JFrame frame = new JFrame();
var closeButtonClickCounter = 0;
...
frame.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        closeButtonClickCounter++;      
    }
});

相关问题