Java 如何从父组件(JFrame)访问子对象
我有一个顶级容器(JFrame),它包含两个JPanel。其中一个JPanel子项具有一个将要更改的属性,该属性需要触发对另一个JPanel组件(JProgressBar)的更新Java 如何从父组件(JFrame)访问子对象,java,swing,user-interface,Java,Swing,User Interface,我有一个顶级容器(JFrame),它包含两个JPanel。其中一个JPanel子项具有一个将要更改的属性,该属性需要触发对另一个JPanel组件(JProgressBar)的更新 如何从触发属性更改的JPanel访问此组件?如果这不是正确的方法,是否有其他方法将属性更改传播到它?听起来您需要使用某种类型的。下面是一个简单的例子,让JFrame知道面板中的属性更改,然后相应地更新另一个面板。如果你的设计变得复杂,并且你有许多不同的组件必须知道彼此的变化,那么你应该考虑. import java.a
如何从触发属性更改的JPanel访问此组件?如果这不是正确的方法,是否有其他方法将属性更改传播到它?听起来您需要使用某种类型的。下面是一个简单的例子,让JFrame知道面板中的属性更改,然后相应地更新另一个面板。如果你的设计变得复杂,并且你有许多不同的组件必须知道彼此的变化,那么你应该考虑.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ObserverFrame extends JFrame {
Panel1 panel;
JPanel panel2;
JLabel label;
//to kick off the example
public static void main(String args[]){
new ObserverFrame();
}
//constructor of the JFrame
public ObserverFrame(){
super("Observer Example");
//the panel that we want to observe
//notice that we pass a reference to the parent
panel = new Panel1(this);
add(panel, BorderLayout.NORTH);
//another panel to be updated when the property changes
panel2 = new JPanel();
label = new JLabel("Panel to be updated");
panel2.add(label);
add(panel2, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
//this method will be called by the panel when the property changes.
public void trigger(Panel1 panel) {
label.setText(String.valueOf(panel.getProperty()));
}
//inner class for convenience of the example
class Panel1 extends JPanel{
ObserverFrame parent;
JButton b1;
private int property;
//accept the parent
public Panel1(ObserverFrame p){
this.parent = p;
b1 = new JButton("Click Me");
//click the button to change the property
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setProperty(getProperty() * 2); //update property here
}
});
property = 10;
add(b1);
}
//the property that we care about
public int getProperty() {
return property;
}
//when the setter is called, trigger the parent
public void setProperty(int property) {
this.property = property;
parent.trigger(this);
}
}
}