我想从JScrollPane中的滚动条中删除滚动条箭头按钮。我该怎么做?
答案 0 :(得分:3)
class NoArrowScrollBarUI extends BasicScrollBarUI {
protected JButton createZeroButton() {
JButton button = new JButton("zero button");
Dimension zeroDim = new Dimension(0,0);
button.setPreferredSize(zeroDim);
button.setMinimumSize(zeroDim);
button.setMaximumSize(zeroDim);
return button;
}
@Override
protected JButton createDecreaseButton(int orientation) {
return createZeroButton();
}
@Override
protected JButton createIncreaseButton(int orientation) {
return createZeroButton();
}
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
//own painting if needed
}
@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
//own painting if needed
}
}
删除按钮可以留出空间。我发现make按钮为零是最简单的方法。
答案 1 :(得分:2)
如果您使用的是JScrollBar的基本版本,则可能使用BasicScrollBarUI进行渲染。我建议您扩展BasicScrollBarUI以创建自定义UI类(如MyBasicScrollBarUI)。按钮是超类中的受保护变量。因此,您需要覆盖子类中的installComponents()方法,并确保不添加按钮。请参阅下面的代码段并隐藏那里的建议行。
protected void installComponents(){
switch (scrollbar.getOrientation()) {
case JScrollBar.VERTICAL:
incrButton = createIncreaseButton(SOUTH);
decrButton = createDecreaseButton(NORTH);
break;
case JScrollBar.HORIZONTAL:
if (scrollbar.getComponentOrientation().isLeftToRight()) {
incrButton = createIncreaseButton(EAST);
decrButton = createDecreaseButton(WEST);
} else {
incrButton = createIncreaseButton(WEST);
decrButton = createDecreaseButton(EAST);
}
break;
}
scrollbar.add(incrButton); // Comment out this line to hide arrow
scrollbar.add(decrButton); // Comment out this line to hide arrow
// Force the children's enabled state to be updated.
scrollbar.setEnabled(scrollbar.isEnabled());
}
然后,在初始化JScrollBar之后的代码中,可以调用setUI()并传入MyBasicScrollBarUI类的实例。
注意:我自己没有尝试过,但从代码看起来它可以正常工作。
答案 2 :(得分:0)
这不是最优雅的方式......但对我有用
JScrollBar jsb = getHorizontalScrollBar();
for(Component c : jsb.getComponents()) {
jsb.remove(c);
}
答案 3 :(得分:0)
这就是我走的路。
never
MouseWheelListener
此方法:
L&F
的好处。以下是用于删除verticall scroll bar
的示例代码。
JScrollPane myScrollPane = new JScrollPane();
//remove the scroll bar you don't want
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
JTextPane myJTextArea = new JTextPane();
//myScrollPane.setViewportView(myJTextArea);
myScrollPane.addMouseWheelListener(new MouseWheelListener() {
//this will mimick the behavior of scrolling
public void mouseWheelMoved(MouseWheelEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
//capturing previous value
int previousValue = scrollBar.getValue();
int addAmount;
//decide where the wheel scrolled
//depending on how fast you want to scroll
//you can chane the addAmount to something greater or lesser
if(e.getWheelRotation()>0) {
addAmount = 2;
}else {
addAmount = -2;
}
//set the new value
scrollBar.setValue(previousValue + addAmount);
}
});