【问题标题】:How auto scroll to position of a focusable JTextField?如何自动滚动到可聚焦 JTextField 的位置?
【发布时间】:2016-10-09 16:51:44
【问题描述】:

我正在使用一个 JScrollPane 容器,其中包含一个 JPanel。 JPanel 里面有很多标签和JTextFields。现在最后一个 JTextField 没有在开始时显示,我想使用 TAB 按钮进入它,并且还让 垂直滚动条滚动到它。

我试过了

DefaultCaret caret = (DefaultCaret) textField.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

还有:

scrollRectToVisible( textField.getBounds() );  

'

没用:(

这是代码:

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                InsertNewOrderWindow frame = new InsertNewOrderWindow();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public InsertNewOrderWindow() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 903, 1001);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));

    JPanel panel = new JPanel();

    JScrollPane scrollPane = new JScrollPane(panel , JScrollPane.VERTICAL_SCROLLBAR_ALWAYS , JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setPreferredSize(new Dimension(300, 577));
    contentPane.add(scrollPane);

    ...... // gridBag stuff

    textField = new JTextField();
    textField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {


            DefaultCaret caret = (DefaultCaret) textField.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);


        }
    });

    ... // gridBag stuff
    panel.add(textField, gbc_textField_19);
    ...

} //InsertNewOrderWindow() method

如何自动滚动到可聚焦的 jtextfield?

【问题讨论】:

    标签: java swing jscrollpane jtextfield autoscroll


    【解决方案1】:

    如何自动滚动到可聚焦的 jtextfield?

    查看Scrolling a Form 以获得简单的解决方案。

    该类使用KeyboardFocusManager 监听焦点变化,然后确保具有焦点的组件显示在滚动窗格的视口中。

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 2022-06-18
      相关资源
      最近更新 更多