Swing JCheckBox是基于MVC的。因此,我希望GUI中的复选框使用我的自定义类提供的数据模型。
这就是:
checkBox1被“绑定”到属性isBackgroundShown
checkBox2被“绑定”到属性isResizingEnabled
复选框应基于属性状态,如果更改,属性状态应触发复选框刷新。
发布于 2011-09-10 23:24:12
实际上,AbstractButtons没有一个“真正的”模型(应该可以在按钮之间共享)-- ButtonModel有每个实例的视图状态(按下、武装)和更多类似于数据的状态,比如selected。更糟糕的是,按钮上的selected属性只看起来像一个绑定的属性(使用setter和getter),但不是(从不触发propertyChange)。
您的选择:
发布于 2011-09-12 17:17:48
回答得很好。我想扩展一下你写的选项。
第一个选项:使用PropertyChange实现按钮模型
注意事项:
虽然第二种方法是“标准”方法,但对我来说,这似乎是大量的代码,只有像Netbeans这样的集成开发环境能够为我管理它(很可能是这样),我才对这种解决方案更感兴趣。
//use static if you nest the class
public /*static*/ class ButtonModelWithPropertyChange extends ToggleButtonModel {
public static final String PROP_SELECTED = "test";
@Override
public void setSelected(boolean selected) {
boolean oldSelected = isSelected();
super.setSelected(selected);
propertyChangeSupport.firePropertyChange(PROP_SELECTED, oldSelected, selected);
}
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void addSelectedChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removeSelectedChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
}并使用它:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.JToggleButton.ToggleButtonModel;
public class TestCheckBoxWithMVC extends JFrame {
public static void main(String [] args) {new TestCheckBoxWithMVC().setVisible(true);}
//my checkbox AND my "bounded" property
JCheckBox myCheckBox = new JCheckBox("my checkbox");
ButtonModelWithPropertyChange buttonModel;
public boolean myProperty;
//my button to test to assign the property and see the checkbox changed accordingly
JButton testBtn = new JButton("Assigning property directly");
public boolean isMyProerty() {
return myProperty;
}
//my property setter that sets the selected value of the model of the checkbox too
public void setMyProperty(boolean b) {
myProperty = b;
buttonModel.setSelected(b);
}
public TestCheckBoxWithMVC() {
super();
setLayout(new FlowLayout());
buttonModel = new ButtonModelWithPropertyChange();
buttonModel.addSelectedChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
myProperty = (Boolean)evt.getNewValue();
}
});
myCheckBox.setModel(buttonModel);
add(myCheckBox);
testBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setMyProperty(!isMyProerty());
}
});
add(testBtn);
pack();
}
//insert here the ButtonModelWithPropertyChange uncommenting static OR put it in
//an ad hoc file.
}https://stackoverflow.com/questions/7371968
复制相似问题