简体   繁体   English

Java Swing组件初始化

[英]Java Swing component initialisation

Is it a good practice to put the initialisation code of a component in a method if it is more than just setting its colour, size and text? 如果不仅仅是将组件的初始化代码设置为颜色,大小和文本,那么将初始化代码放入方法中是否是一种好习惯?

// frame initialisation
public void init()
{
    .....

    sectors = new JSlider(10,50,12);
    initSlider();

    .....
}

public void initSlider()
{
    sectors.setMinorTickSpacing(1);
    sectors.setMajorTickSpacing(5);
    sectors.setSnapToTicks(true);
    sectors.setPaintLabels(true);
    sectors.setPaintTicks(true);
}

Yes it would be better and it would also make it easier to manage and read the code. 是的,这样做会更好,并且也将使管理和阅读代码更加容易。 This is what i think but at the end of the day it is up to the style of the programmer. 这就是我的想法,但归根结底,这取决于程序员的风格。

There is no harm in doing this, however, I would recommend you to move the initialisation into its own separate class to have a clean separation of concern. 这样做没有什么害处,但是,我建议您将初始化移到其自己的单独的类中,以实现清晰的关注点分离。

class MySlider extends JSlider{
    public MySlider(){
       super();
       //init statements here
    }
}

Then in your frame/main class 然后在您的框架/主班

public void init()
{
    .....
    sectors = new MySlider(10,50,12);
    .....
}

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

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