当前位置: 首页 > 知识库问答 >
问题:

如何在组件之间更改焦点

宦翔
2023-03-14

我创建了一个Jframe,它由Jbutton(Ok)、Jbutton(cancel)、Jtextfield和一个Jtable组成。我想当按下OK按钮时,焦点变为Jtextfield,当按下增益按钮时,焦点变为JTable。

如何在组件之间更改焦点?

这就是我尝试过的:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            try{
                Robot robot = new Robot();
          
            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            
            KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
               }

            catch (AWTException ex) {
            Logger.getLogger(testSoso.class.getName()).log(Level.SEVERE, null, ex);
        }

        }  

它只关注JTextfield,但不会将焦点更改为JTable

编辑:我也试过:

KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(JTable2);

但没有奏效

这是整个代码

package javaapplication5;

import java.awt.AWTException;
import java.awt.KeyboardFocusManager;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Dell
 */
public class javaApp5 extends javax.swing.JFrame {

    /**
     * Creates new form testSoso
     */
    public javaApp5() {
        initComponents();
        
      
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton2.setText("cancel");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(40, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(60, 60, 60))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextField1)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE))
                        .addGap(192, 192, 192))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(65, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
      //  for(int i=0;i<4;i++){
        //  jTable2.addRowSelectionInterval(0,0);
        try {
            Robot robot = new Robot();
            
            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            
            KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
            
        } catch (AWTException ex) {
            Logger.getLogger(javaApp5.class.getName()).log(Level.SEVERE, null, ex);
        }
       // }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(javaApp5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(javaApp5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(javaApp5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(javaApp5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new javaApp5().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}
     

共有1个答案

慕高阳
2023-03-14

当用户单击OK按钮时,键盘焦点将转移到该按钮。因此,通过classRobot模拟按下TAB键将键盘焦点转移到下一个组件,即取消按钮。

简单地调用requestFocusInWindow方法对我来说很有效。我添加了一个名为txtFld的布尔类成员变量,以便知道哪个组件需要获得焦点。

以下是我的方法版本jButton1ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (txtFld) {
        jTable2.requestFocusInWindow();
    }
    else {
        jTextField1.requestFocusInWindow();
    }
    txtFld = !txtFld;
}

不需要类Robot也不需要类KeyboardFocus usManager

为了完整起见,这是您的代码和我的更改。

package javaapplication5;

public class javaApp5 extends javax.swing.JFrame {

    /**
     * Creates new form testSoso
     */
    public javaApp5() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{{null, null, null, null},
                               {null, null, null, null},
                               {null, null, null, null},
                               {null, null, null, null}},
                new String[]{"Title 1", "Title 2", "Title 3", "Title 4"}));
        jScrollPane2.setViewportView(jTable2);
        jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton2.setText("cancel");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap(40, Short.MAX_VALUE)
                        .addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createSequentialGroup().addComponent(jScrollPane2,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 374,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(60, 60, 60))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(
                                                        javax.swing.GroupLayout.Alignment.TRAILING,
                                                        false)
                                                .addComponent(jTextField1)
                                                .addComponent(jButton1,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        Short.MAX_VALUE)
                                                .addComponent(jButton2,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, 103,
                                                        Short.MAX_VALUE))
                                                .addGap(192, 192, 192)))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addGap(47, 47, 47)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        167, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(65, Short.MAX_VALUE)));
        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        if (txtFld) {
            jTable2.requestFocusInWindow();
        }
        else {
            jTextField1.requestFocusInWindow();
        }
        txtFld = !txtFld;
    }

    /**
     * @param args - the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        // <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
        // (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the default
         * look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                    .getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }
        // </editor-fold>
        // </editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new javaApp5().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private boolean txtFld;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

顺便说一句,如果你正在学习Swing,我建议不要使用你的IDE的GUI生成器。

 类似资料:
  • 当将html输入与样式化组件一起使用并将值保存为react state with onChange时,组件似乎会在每次状态更改时重新呈现,并导致输入失去焦点。有没有办法防止输入失去焦点?为什么会发生这种情况?这里有一个例子。

  • 我正在一个活动的登录页面上工作,其中用户名和密码作为两个编辑文本框。当焦点从用户名更改为密码框时,我试图显示Toast消息:-如果在用户名框中输入的文本中有空格-如果没有空格,则不显示Toast。

  • 问题内容: JavaFX是否可以像AWT一样更改 焦点遍历策略 ? 因为我的两个ES 的遍历顺序是错误的。 问题答案: 在通常情况下,导航以容器顺序,子顺序或按箭头键进行。您可以更改节点的顺序-在这种情况下,这将是您的最佳解决方案。 JFX中有一个关于遍历引擎策略替换的后门: 您可以继承内部类com.sun.javafx.scene.traversal.TraversalEngine 并使用 调用

  • 问题内容: 我是Redis的新手,但我不知道如何创建和更改到另一个Redis数据库。 我该怎么做呢? 问题答案: 默认情况下,有16个数据库(索引从0到15),您可以使用select命令在它们之间导航。可以通过设置在redis配置文件中更改数据库数量。 默认情况下,它选择数据库。要选择一个指定的,使用 (选择数据库2)

  • 我正在创建一个支持多重选择的QML,并将在我的应用程序中实例化其中的多个。我需要将键盘焦点赋予特定列表,处理该列表的按键,并根据焦点为选定的行绘制高亮显示。 但是,将赋予ListView委托或ListView本身并不会导致在ListView上出现,也不会导致触发按键信号。 我创建了一个简单的示例应用程序,展示了我的问题: 单击任一列表都不会将选定的行变成粉红色,按上/下键也不会调整选定内容。 如何

  • 在按钮悬停我想做的改变:之前的内容太,我找不到一个答案在官方留档我想知道这是可能的。 这里是样式组件: