将自定义的Java Swing组件属性设置为默认值。

huangapple go评论61阅读模式
英文:

set defalut value to custom java swing component property

问题

我正在尝试创建一个自定义按钮。

public class MyButton extends JButton implements PropertyChangeListener {

}

我想要为这个按钮的某个属性设置一个默认值。例如,如果用户没有设置任何值作为foreground_color,我希望将其设置为Color.RED。

如果用户设置了任何颜色作为foreground_color,按钮应该忽略默认颜色。

这是否可行?

英文:

I'm trying to create a custom button.

public class MyButton extends JButton implements PropertyChangeListener {

}

and I want to set a default value to some property in this button. I.E. if user not set any value as foreground_color I want to set it as Color.RED

if user set any color as foreground_color the button should ignore the default color.

is it possible to do?

答案1

得分: 0

可以在你的 MyButton 类中添加一个构造函数来设置默认值。当然,这些默认值可以在后面使用 myButton.setForeground() 等方法进行覆盖:

public MyButton() {
    super();
    setForeground(Color.RED);
    // ... 
}

如果你想保留 JButton 中的任何特殊构造函数(例如,接受按钮文本的构造函数),你当然可以修改此构造函数或添加另一个构造函数:

public MyButton(String text) {
    super(text);
    setDefaults();
}

private void setDefaults() {
    setForeground(Color.RED);
    // ... 更多默认设置 ...
}
英文:

Yes, you can add a constructor to your MyButton class that sets the default values. Of course these can be overwritten later with myButton.setForeground() etc.:

public MyButton() {
	super();
	setForeground(Color.RED);
	// ... 
}

If you want to keep any special constructors from JButton (e.g. the one that takes a string for a button text), you can of course modify this or add another one:

public MyButton(String text) {
	super(text);
	setDefaults();
}

private void setDefaults() {
	setForeground(Color.RED);
	// ... more defaults ...
}

huangapple
  • 本文由 发表于 2020年8月10日 17:57:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63337990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定