按住按钮时如何使JButton执行? [英] How to make the JButton execute when holding the button?

查看:104
本文介绍了按住按钮时如何使JButton执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我的程序非常简单.我只需要单击或按Alt +输入JButton即可增加计数器.

First, my program is very simple. I just need to click or press Alt + Enter the JButton to increment the counter.

这是程序,因此您可以尝试:

Here is the program so you can try it:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class holdDownClass implements ActionListener {
    private static JButton exebouton;
    private JTextArea ecran = new JTextArea();
    private JScrollPane scrollecran = new JScrollPane(ecran);
    private int counter = 0;

    public static void main(String[] args) {
        new holdDownClass();
    }

    private holdDownClass() {
        // Window
        JFrame frame = new JFrame("Name");
        frame.setBounds(400, 350, 625, 355);
        frame.setLayout(null);

        Container container = frame.getContentPane();

        // Panel
        JPanel panneau = new JPanel();
        panneau.setLayout(null);
        panneau.setBounds(2, 42, 146, 252);
        frame.add(panneau);

        JLabel nglabel = new JLabel("Click or Press Alt+Enter");
        nglabel.setBounds(5, 0, 200, 20);
        panneau.add(nglabel);

        // Button
        exebouton = new JButton("Execute");
        exebouton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
        exebouton.setBounds(4, 18, 138, 47);
        exebouton.addActionListener(this);
        panneau.add(exebouton);

        // Text Area
        ecran.setEditable(true);
        scrollecran.setBounds(150, 42, 467, 252);
        container.add(scrollecran);

        // Show
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object test = e.getSource();         
        if (test.equals(exebouton)) {
            counter += 1;
            ecran.setText(ecran.getText() + counter + "\n");
        }
    }
}

我的目标是:我要按住Alt + Enter而不是重复按Alt + Enter来增加计数器"Quicker".

推荐答案

这是您可以做到的方式-

Here's the way you can do it-

private boolean mousePressed;

还有一个鼠标侦听器-

     exebouton.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            mousePressed = true;
            new Thread() {
                public void run() {
                    while (mousePressed) {
                        counter += 1;
                        ecran.setText(ecran.getText() + counter + "\n");
                    }
                }

            }.start();
        }

        public void mouseReleased(MouseEvent e) {
            mousePressed = false;
        }

    });

就是这样.

这篇关于按住按钮时如何使JButton执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆