当JScrollPane中的JList没有填充整个区域时,如何禁用JScrollBar



jlist中只有几行时,我不希望滚动条能够向下滚动,因为没有必要。此外,我可以单击空的行,这会高亮显示该行,即使它是空的。如何禁用高亮显示行的功能?

    public ProductApplication()
    {
    //WEST PANEL
    JPanel west = new JPanel(new BorderLayout());
    west.setBorder(BorderFactory.createMatteBorder(
            5, 5, 5, 5, Color.blue));
    west.add(new JTextField("Products"),
            BorderLayout.NORTH);
    pList = new JList(product);
    pList.setFixedCellHeight(20);
    pList.setFixedCellWidth(100);
    west.add(pList, BorderLayout.CENTER);
    scrollpane = new JScrollPane(pList);
    west.add(scrollpane, BorderLayout.WEST);
    add(west, BorderLayout.WEST);

1)如果不需要显示JScrollBar,只需创建JScrollPane,如下所示:

JScrollPane jScrollPane = new JScrollPane(list);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

2) 您可以在ListCellRenderer的帮助下管理高亮显示能力。

试试下一个例子:

import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame {
    public TestFrame(){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                init();
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                pack();
                setVisible(true);
            }
        });
    }
    private void init() {
        DefaultListModel<String> model;
        JList<String> l = new JList<>(model = new DefaultListModel<>());
        l.setFixedCellHeight(20);
        l.setFixedCellWidth(100);
        model.addElement("");
        for(int i=0;i<5;i++){
            model.addElement(i+"");
        }
        model.addElement("");
        model.addElement("5");
        l.setCellRenderer(getRenderer());
        JScrollPane jScrollPane = new JScrollPane(l);
        jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        add(jScrollPane);
    }
    private ListCellRenderer<? super String> getRenderer() {
        return new DefaultListCellRenderer(){
            @Override
            public Component getListCellRendererComponent(JList<?> list,Object value, int index, boolean isSelected,boolean cellHasFocus) {
                Component listCellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
                if((value == null || value.toString().isEmpty()) && isSelected){
                    listCellRendererComponent.setBackground(list.getBackground());
                    ((JComponent)listCellRendererComponent).setBorder(null);
                }
                return listCellRendererComponent;
            }
        };
    }
    public static void main(String... s){
        new TestFrame();
    }
}

相关内容

  • 没有找到相关文章