API提到, “java.awt.Graphics
用户剪辑和设备剪辑的组合定义了复合剪辑,它决定了最终的剪辑区域”,但剪辑与您的问题并不真正相关。相反,您可能想要使用合适的布局。允许使用不可见组件作为填充物的框布局在这种情况下可能很有用。
附录:
我宁愿...覆盖paintComponent()
在JSlider
.
AFAIK,paintComponent()
只是委托给javax.swing.plaf.SliderUI
. 这个例子可能会建议一种方法。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
/** @see https://stackoverflow.com/questions/3971972 */
public class JSliderTest extends JPanel {
public JSliderTest() {
super(new GridLayout(0, 1));
this.setPreferredSize(new Dimension(500, 400));
this.add(genSliderPanel());
this.add(genSliderPanel());
this.add(genSliderPanel());
}
private JPanel genSliderPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
JSlider slider = new JSlider(JSlider.HORIZONTAL);
slider.setValue(40);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
panel.add(Box.createVerticalGlue());
panel.add(slider);
panel.add(Box.createRigidArea(new Dimension(16, 16)));
return panel;
}
private void display() {
JFrame f = new JFrame("JSliderTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new JSliderTest().display();
}
});
}
}