为了在我的其他问题中保持秩序,建议分别询问以下内容:
以下是测试类的代码,我在其中添加了自定义JScrollBar
public class TestScrollBar {
private static JFrame f;
private static Container pane;
private static JScrollPane scroll1;
private static JScrollBar scrollbar;
private static JPanel panel;
private static JList<String> list1;
public static void main(String[] arg){
createBasic();
createComponents();
f.setVisible(true);
}
private static void createBasic(){
f = new JFrame("ScrollbarTest");
f.setBounds(100,100,300,300);
pane = f.getContentPane();
pane.setLayout(null);
panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.setLayout(null);
panel.setBounds(50,50,200,150);
}
private static void createComponents(){
String[] data = {"ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg", "ggggg"};
list1 = new JList<String>(data);
list1.setBackground(new Color(0,0,0,0));
scrollbar = new JScrollBar();
CustomScrollBarUI ui = new CustomScrollBarUI();
scrollbar.setUI(ui);
scrollbar.setOpaque(false);
scroll1 = new JScrollPane(list1);
scroll1.setBounds(20,20,160,110);
scroll1.setOpaque(false);
scroll1.getViewport().setOpaque(false);
scroll1.setVerticalScrollBar(scrollbar);
panel.add(scroll1);
pane.add(panel);
}
}
可以在此处看到自定义ScrollBarUI:Custom JScrollBar-Thumb is painted, but doesn't move
我改变的唯一一件事(感谢mgarin)是
g.drawImage(img, thumbBounds.x, thumbBounds.y, new Color(255,255,255,0), null);
以下情况发生,如果我移动拇指(请不要介意设计,只是测试一些不透明的东西......)
答案 0 :(得分:2)
您使列表的背景透明;
list1.setBackground(new Color(0,0,0,0));
如果删除该行,则可以正常使用。
另外请注意:如果要为单元格指定自定义背景颜色,请尝试使用自定义ListCellRenderer,使用JList上的setCellRenderer()方法。然后,您可以设置返回的组件的背景颜色。