2011-12-23 30 views
15

He experimentado y buscado y parece que no puedo entender lo que pensé que sería algo simple, que es tener mi botón START enfocado cuando mi pequeña aplicación GUI se ejecuta, es decir, todo lo que el usuario tiene que hacer es presionar su tecla Enter/Return, que tendrá el mismo efecto que si hubieran presionado el botón START con su mouse. Aquí está mi código. Gracias por su ayuda :)Java GUI: ¿Cómo establecer el foco en JButton en JPanel en JFrame?

private void initialize() { 

    // Launch the frame: 
    frame = new JFrame(); 
    frame.setTitle("Welcome!"); 
    frame.setSize(520, 480); 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    // Add the image: 
    ImageIcon heroShotImage = new ImageIcon("heroShot.jpg"); 
    JPanel heroShotPanel = new JPanel(); 
    JLabel heroShot = new JLabel(heroShotImage); 
    heroShotPanel.add(heroShot); 

    // Create a panel to hold the "Start" button: 
    JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); 

    // Create the "Start" button, which launches business logic and dialogs: 
    JButton start = new JButton("Start"); 
    start.setToolTipText("Click to use library"); 
    start.setFocusable(true); // How do I get focus on button on App launch? 
    start.requestFocus(true); // Tried a few things and can't get it to work. 

    // Listen for user actions and do some basic validation: 
    start.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     // THE APP's LOGIC GOES HERE... 
     } 

    // Finish setting up the GUI and its components, listeners, and actions: 
    submitPanel.add(start); 

    frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH); 
     frame.getContentPane().add(submitPanel, BorderLayout.SOUTH); 

} 
+0

1, para él es lo suficientemente amable para decir gracias a todos los que respondieron con una respuesta. Buena suerte con tu trabajo. Saludos –

Respuesta

26

Prueba este código .. Todo lo que he hecho es mover el método requestFocus() al final.

Básicamente estas son las dos cosas que tiene que hacer para que respondan mientras presiona la tecla Entrar y para que se enfoquen por defecto.

frame.getRootPane().setDefaultButton(start); 
start.requestFocus(); 

Screenshot of the image

package sof; 

import java.awt.BorderLayout; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class TestFrame { 

    public static void main(String[] args) { 
     // Launch the frame: 
     JFrame frame = new JFrame(); 
     frame.setTitle("Welcome!"); 
     frame.setSize(520, 480); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     // Add the image: 
     ImageIcon heroShotImage = new ImageIcon("heroShot.jpg"); 
     JPanel heroShotPanel = new JPanel(); 
     JLabel heroShot = new JLabel(heroShotImage); 
     heroShotPanel.add(heroShot); 

     // Create a panel to hold the "Start" button: 
     JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); 

     JButton start = new JButton("Start"); 
     start.setToolTipText("Click to use library"); 

     start.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("I AM PRESSED"); 
      } 
     }); 

     submitPanel.add(start); 

     frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH); 
     frame.getContentPane().add(submitPanel, BorderLayout.SOUTH); 
     frame.setVisible(true); 
     frame.getRootPane().setDefaultButton(start); 
     start.requestFocus(); 
    } 
} 
+0

Gracias por la respuesta :) – chrisco

+1

Lo siento mucho. Soy nuevo aquí e hice un error de novato. Sé que lo sé Nuevamente, lo siento mucho. La próxima vez buscaré la PRIMERA Y MEJOR respuesta. – chrisco

+0

@chrisco: no hay problema y ¡gracias! – bragboy

2

mover su línea de foco al final del método

y el cambio a

start.requestFocus(); // without params 
+0

Gracias por la respuesta :) – chrisco

7

Si te estoy entendiendo entonces usted quiere hacer un evento de clic de botón de inicio cuando el usuario éxitos tecla Intro. Si este es el caso, entonces usted puede hacerlo de la siguiente manera:

jFrame.getRootPane().setDefaultButton(start);// 'start' will be your start button 

Y si lo que desea es obtener el foco en el botón de inicio a continuación, cambiar su método de requestFocus() al final (después de hacer su marco visible) y no hay necesidad pasar true en él. También es mejor usar requestFocusInWindow() luego requestFocus() como se indica en el documento de Java.

+0

Funciona perfectamente, muchas gracias! – chrisco

3

Si desea que su botón de start para obtener el foco y luego hacer esto al final

//This button will have the initial focus. 
start.requestFocusInWindow(); 
+1

Gracias por la respuesta :) – chrisco

+0

@chrisco No hay problema :) – GETah

Cuestiones relacionadas