2017-08-28 91 views
1

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

我该怎么做?

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

+1

每'JComponent's(例如声明为局部变量)返回其'Bounds',使用这些值从变量作为矩形,宣布为'scrollRectToVisible(JCOmponent.getBounds())参数' – mKorbel

回答

1

A 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); 
    } 
}