简体   繁体   English

自定义Jslider初始化问题

[英]Custom Jslider Initialization Problem

I am working on a custom JSlider that has a custom Track Rectangle. 我正在开发具有自定义轨道矩形的自定义JSlider。 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. 在上面的代码中,“ kolor”最初为null,并在NewSliderUI尝试使用它时导致和错误。 It appears that the updateUI() method is called before anything else. 似乎在其他任何东西之前都调用了updateUI()方法。 Then the NewSlider constructor is called. 然后调用NewSlider构造函数。 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. 我已经尝试了多种方法,但是因为updateUI()似乎先于其他任何东西运行,所以我添加到NewSlider类中的任何内容似乎都没有关系。

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. 如果我对颜色进行硬编码(即setUI(new NewSliderUI(this, Color.BLACK); )),则可以工作,但是每种颜色具有不同的类似乎很愚蠢。

Thanks. 谢谢。

I don't see how kolor could be null unless one of the following are happening: 除非发生以下情况之一,否则我看不出kolor如何为null:

  1. You're passing a null value to the constructor 您正在将null值传递给构造函数
  2. You're not instantiating NewSlider in the Swing EDT and are having some strange cache issues 您没有在Swing EDT中实例化NewSlider,并且遇到了一些奇怪的缓存问题
  3. NewSlider is being constructed via reflection/deserialization and kolor is not being set. 正在通过反射/反序列化构造NewSlider,并且未设置kolor。

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). 我很好奇要确保调用了NewSlider构造函数(并且在NewSliderUI构造函数之前)。

Edit: I see what you mean below. 编辑:下面我明白你的意思。 I forgot that the no args constructor for JSlider was being called implicitly. 我忘记了JSlider的no args构造函数被隐式调用。 What about doing the following: 如何执行以下操作:

public class NewSlider extends JSlider {

   Color kolor = Color.BLACK;

   public NewSlider (Color k) {    
      kolor = k;
      updateUI();
   }

   public void updateUI() {
      setUI(new NewSliderUI(this, kolor);
      updateLabelUIs();
   }
}

You end up calling updateUI() twice, but the end result should be what you want. 您最终两次调用了updateUI(),但是最终结果应该是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM