【问题标题】:Java JComboBox scroll to selected itemJava JComboBox 滚动到所选项目
【发布时间】:2017-08-28 12:19:34
【问题描述】:

我有一个包含数据的网格和一个JComboBox,其中有很多用户,其中一个被选中。我想将所选项目滚动到用户看不到其余数据的区域(网格底部),以便我的JScrollPane 会自动跳转到该区域。

我该怎么做?

我认为这与scrollRectToVisible() 方法有关。

【问题讨论】:

  • 每个JComponents(例如声明为局部变量)都返回其Bounds,将变量中的这些值用作矩形,声明为scrollRectToVisible(JCOmponent.getBounds())的参数

标签: java swing jscrollpane jcombobox


【解决方案1】:

JComboBox 不需要 JScrollPane

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class OneLineCombo {

    private JComponent ui = null;

    OneLineCombo() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,20,4,20));

        String[] fontFamily = GraphicsEnvironment.
                getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        JComboBox fontCombo = new JComboBox(fontFamily);
        fontCombo.setMaximumRowCount(1);
        ui.add(fontCombo, BorderLayout.PAGE_START);
        ui.add(new JLabel("Type some letters of the font name to select it"), 
                BorderLayout.PAGE_END);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                OneLineCombo o = new OneLineCombo();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

【讨论】:

    猜你喜欢
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2013-10-26
    • 2017-05-21
    • 2012-06-14
    相关资源
    最近更新 更多