java jtabbedpane 焦点_Java Swing - 如何使JScrollPane滚动以跟随输入焦点

import java.awt.KeyboardFocusManager;

import java.awt.Rectangle;

import java.beans.PropertyChangeEvent;

import java.beans.PropertyChangeListener;

import javax.swing.BoxLayout;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTextField;

import javax.swing.JViewport;

public class Main {

public static void main(String[] args) {

int ROWS = 100;

JPanel content = new JPanel();

content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));

content.add(new JLabel("Thanks for helping out. Use tab to move around."));

for (int i = 0; i < ROWS; i++) {

JTextField field = new JTextField("" + i);

field.setName("field#" + i);

content.add(field);

}

KeyboardFocusManager.getCurrentKeyboardFocusManager()

.addPropertyChangeListener("focusOwner", new PropertyChangeListener() {

@Override

public void propertyChange(PropertyChangeEvent evt) {

if (!(evt.getNewValue() instanceof JComponent)) {

return;

}

JViewport viewport = (JViewport) content.getParent();

JComponent focused = (JComponent) evt.getNewValue();

if (content.isAncestorOf(focused)) {

Rectangle rect = focused.getBounds();

Rectangle r2 = viewport.getVisibleRect();

content.scrollRectToVisible(new Rectangle(rect.x, rect.y,

(int) r2.getWidth(), (int) r2.getHeight()));

}

}

});

JFrame window = new JFrame();

window.setContentPane(new JScrollPane(content));

window.setSize(200, 200);

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

window.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值