Sto implementando un codice di tastiera per un'applicazione java swing esistente, ma non riesco a ottenere una pressione della tastiera per eseguire l'azione "mousePressed" e l'azione "mouseReleased" mappate su un JButton. Non ho problemi a cliccarlo per "action_performed" con button.doClick(), c'è una funzione simile per simulare le presse del mouse? Grazie in anticipo.Come si simula un clic completo con Java Swing?
5
A
risposta
6
È possibile simulare presse del mouse e le azioni del mouse utilizzando la classe Robot. È realizzato per la simulazione ad es. per testare automaticamente le interfacce utente.
Ma se si desidera condividere "azioni" per es. pulsanti e pressioni dei tasti, è necessario utilizzare uno Action
. Vedi How to Use Actions.
esempio su come condividere un'azione per un pulsante e la pressione dei tasti:
Action myAction = new AbstractAction("Some action") {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
};
// use the action on a button
JButton myButton = new JButton(myAction);
// use the same action for a keypress
myComponent.getInputMap().put(KeyStroke.getKeyStroke("F2"), "doSomething");
myComponent.getActionMap().put("doSomething", myAction);
Leggi tutto su Key-binding su How to Use Key Bindings.
2
Cercare di utilizzare un Robot
per simulare le pressioni della tastiera e l'attività del mouse.
2
Si potrebbe aggiungere un listener per il pulsante:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonAction {
private static void createAndShowGUI() {
JFrame frame1 = new JFrame("JAVA");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(" >> JavaProgrammingForums.com <<");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}`
controllo questo http://stackoverflow.com/questions/2445105/how-do-you-simulate-a-click-on-a-jtextfield -equivalent-di-JButton-DoClick – doNotCheckMyBlog