首先,我的程序很簡單。我只需要點擊或按Alt +輸入JButton來遞增計數器。如何在按住按鈕時執行JButton?
這裏的程序,所以你可以嘗試一下:
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鍵遞增計數器「更快」。
你嘗試處理鼠標按下和鼠標釋放事件。按下鼠標時開始遞增,釋放鼠標時開始遞增。 –
@Sudhanshu我沒有嘗試。我不知道如何去做。我該怎麼做? –
爲你將不得不KeyListener的註冊到''JButton''exebouton –