自定义Jslider初始化问题
我正在开发一个具有自定义轨道矩形的自定义 JSlider。我希望能够在首次声明滑块时设置轨道矩形的颜色。
这是我所拥有的片段(这些类位于同一包中的单独文件中):
public class NewSlider extends JSlider {
Color kolor;
public NewSlider (Color k) {
kolor = k;
}
public void updateUI() {
setUI(new NewSliderUI(this, kolor);
updateLabelUIs();
}
}
public class NewSliderUI extends BasicSliderUI {
Color sliderColor = Color.BLACK;
public NewSliderUI (JSlider b, Color k) {
super(b);
sliderColor = k;
}
}
在上面的代码中,“kolor”最初为空,当 NewSliderUI 尝试使用它时会导致错误。看起来 updateUI()
方法是在其他任何事情之前调用的。然后调用 NewSlider 构造函数。我尝试了多种方法,但由于 updateUI() 似乎先于其他任何操作运行,因此我添加到 NewSlider 类中的任何内容似乎都不重要。
如果我硬编码一个颜色(即 setUI(new NewSliderUI(this, Color.BLACK);
),那么它可以工作,但是为每种颜色设置不同的类似乎很愚蠢。
谢谢。
I am working on a custom JSlider that has a custom Track Rectangle. I want the ability to set the color of the track rectangle when first declaring the slider.
Here's a snippet of what I have (The classes are in separate files in the same package):
public class NewSlider extends JSlider {
Color kolor;
public NewSlider (Color k) {
kolor = k;
}
public void updateUI() {
setUI(new NewSliderUI(this, kolor);
updateLabelUIs();
}
}
public class NewSliderUI extends BasicSliderUI {
Color sliderColor = Color.BLACK;
public NewSliderUI (JSlider b, Color k) {
super(b);
sliderColor = k;
}
}
In the above code, "kolor" is initially null and leads to and error when NewSliderUI tries to use it. It appears that the updateUI()
method is called before anything else. Then the NewSlider constructor is called. I have tried a variety of things, but because updateUI() appears to run before anything else, nothing I add to the NewSlider class seems to matter.
If I hardcode a Color (ie. setUI(new NewSliderUI(this, Color.BLACK);
), then it works, but having a different class for each color seems silly.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白 kolor 怎么可能为空,除非发生以下情况之一:
您是否尝试过在调试器中使用一些断点运行它?我很想确保调用 NewSlider 构造函数(并且在 NewSliderUI 构造函数之前)。
编辑:我明白你的意思了。我忘记了 JSlider 的无参数构造函数是被隐式调用的。执行以下操作怎么样:
您最终调用 updateUI() 两次,但最终结果应该是您想要的。
I don't see how kolor could be null unless one of the following are happening:
Have you tried running this in the debugger with some breakpoints? I'd be curious to ensure that the NewSlider constructor is being called (and before the NewSliderUI constructor).
Edit: I see what you mean below. I forgot that the no args constructor for JSlider was being called implicitly. What about doing the following:
You end up calling updateUI() twice, but the end result should be what you want.