如何访问方法 "across" JButton 的层次结构?
How to access methods "across" a hierarchy of JButtons?
我有两种扩展 JButton
的按钮,我需要一个按钮来访问另一个按钮的 get 方法。但是因为 isPressed()
方法不是按钮的一部分,所以我无法调用它。
说明:我有一种按钮。当我按下那个按钮时,一个布尔值被设置为 true。我想要另一个按钮来访问该布尔值。
public class EmptySpace extends JButton {
protected int x;
protected int y;
protected String name;
public EmptySpace(String text, int x, int y){
super(text);
this.name = text;
this.x = x;
this.y = y;
addMouseListener(new MouseAdapter(){
@Override
public void mouseEntered(MouseEvent e){
Board.toStringText.setText(e.getSource().toString());
}
});
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
if(Board.buildButton.getIsPressed()){ //ERROR HERE
}
}
});
}
public String toString(){
return "Name: " + name + " Xcoords: " + x + " Ycoords: " + y;
}
public class BuildButton extends JButton {
boolean isPressed = false;
public BuildButton(){
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
isPressed = true;
Board.BuildIsPressed.setText( "Building : "+ boardRunner.numberOfbiulds +" builds left.");
}
});
}
public boolean getIsPressed(){
return isPressed;
}
您的解决方案是将您的模型与 GUI 分开,将 ActionListener 添加到一个按钮,并在该侦听器中,在您的程序模型中设置一个布尔值。然后另一个按钮的 ActionListener 可以在需要时访问该状态。
其他方面推荐:
- 避免过度使用继承,一般来说有利于组合。
- 避免将 MouseListeners 与 JButton 一起使用,因为这会改变 JButton,使它们的行为不像预期的那样 -- space 栏将停止在聚焦的 JButton 上工作,JButton 的操作即使在禁用时仍会发生。
我有两种扩展 JButton
的按钮,我需要一个按钮来访问另一个按钮的 get 方法。但是因为 isPressed()
方法不是按钮的一部分,所以我无法调用它。
说明:我有一种按钮。当我按下那个按钮时,一个布尔值被设置为 true。我想要另一个按钮来访问该布尔值。
public class EmptySpace extends JButton {
protected int x;
protected int y;
protected String name;
public EmptySpace(String text, int x, int y){
super(text);
this.name = text;
this.x = x;
this.y = y;
addMouseListener(new MouseAdapter(){
@Override
public void mouseEntered(MouseEvent e){
Board.toStringText.setText(e.getSource().toString());
}
});
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
if(Board.buildButton.getIsPressed()){ //ERROR HERE
}
}
});
}
public String toString(){
return "Name: " + name + " Xcoords: " + x + " Ycoords: " + y;
}
public class BuildButton extends JButton {
boolean isPressed = false;
public BuildButton(){
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
isPressed = true;
Board.BuildIsPressed.setText( "Building : "+ boardRunner.numberOfbiulds +" builds left.");
}
});
}
public boolean getIsPressed(){
return isPressed;
}
您的解决方案是将您的模型与 GUI 分开,将 ActionListener 添加到一个按钮,并在该侦听器中,在您的程序模型中设置一个布尔值。然后另一个按钮的 ActionListener 可以在需要时访问该状态。
其他方面推荐:
- 避免过度使用继承,一般来说有利于组合。
- 避免将 MouseListeners 与 JButton 一起使用,因为这会改变 JButton,使它们的行为不像预期的那样 -- space 栏将停止在聚焦的 JButton 上工作,JButton 的操作即使在禁用时仍会发生。