我知道这是一个令人困惑的标题,但我会尽力在这里更好地解释它。我目前正在尝试创建一个游戏,并希望拥有在整个游戏中执行不同操作的按钮。我认为有这样的方法就足够简单了:
public void ButtonCreation(String bText, int x, int y, int Width, int Height, int fontSize){
this.Bol = false;
this.btex = bText;
this.bSize = fontSize;
this.by = y;
this.bx = x;
this.bw = Width;
this.bh = Height;
JToggleButton Button = new JToggleButton(bText);
Button.setBackground(new Color(75, 67, 67));
Button.setForeground(Color.BLACK);
Button.setFont(new Font("Arial", Font.BOLD,fontSize));
Button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
Button.setFocusPainted(false);
Button.setSize(Width,Height);
Button.setLocation(x,y);
frame.add(Button);
intro.Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(intro.Button.getModel().isPressed()){
intro.Bol = true; //What Im trying to change when I call the method (as in add more code into here)
}
if(!intro.Button.getModel().isPressed()){
intro.Bol = false;
}
}
});
}
我在不同的类 MainClass 中调用该方法。这是我定期调用它:
intro.ButtonCreation("开始游戏", 550,490,200,50,22);
如果有人对如何访问代码的执行部分并在调用方法时编辑/添加它有想法,我们将不胜感激。
我尝试过在主类中执行操作,然后在创建按钮后对其进行更改,但这不起作用。预先感谢!
将
ActionListener
的实例传递给工厂方法。这支持像依赖注入、单一职责原则这样的概念,它将降低内聚性(即解耦你的代码),使其更容易推理、调试和维护......
public JButton createButton(String bText, int fontSize, ActionListener listener) {
// This seems to be irrelevant - why would you otherwise
// need this information and I would consider it a side
// effect see "single responsibility" for more details
//this.Bol = false;
//this.btex = bText;
//this.bSize = fontSize;
//this.by = y;
//this.bx = x;
//this.bw = Width;
//this.bh = Height;
JToggleButton button = new JToggleButton(bText);
button.setBackground(new Color(75, 67, 67));
button.setForeground(Color.BLACK);
button.setFont(new Font("Arial", Font.BOLD, fontSize));
button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
button.setFocusPainted(false);
// Try not to manually size or position your controls
// Make use of appropriate layout managers instead
button.addActionListener(listener);
return button
// I'd consider this a side effect and a code smell.
// Why should creating the button also add it?
// frame.add(Button);
// No idea what this or why it's here, but immediately, it's
// raising alarm bells.
//intro.Button.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// if (intro.Button.getModel().isPressed()) {
// intro.Bol = true; //What Im trying to change when I call the method (as in add more code into here)
//
// }
//
// if (!intro.Button.getModel().isPressed()) {
// intro.Bol = false;
// }
//
// }
//});
}
您可能还想探索 构建器模式
这可以让你做类似的事情......
JButton btn = new ButtonBuilder(actionListener)
.withText(bText)
.withFontSize(fontSize)
// .. other properties
.build();