我决定使用 BorderLayout 进行名为 Loginwards 的 Swing 设计。我为 BorderLayout 的 5 个边编写了 5 个类,分别为 PageStart、LineStart、Center、LineEnd、PageEnd。
我没有装饰Loginwards,并设计了PageStart以供使用最小化,调整大小,退出。(对于我自己的图像,规则......)按钮退出很简单,因为它的工作原理是这样的
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
但是例如最小化我无法解决。我应该从另一个类对象更改我的 Loginwards 属性
总结
public class Loginwards extends Jframe
{ ...
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(PageStart.Panel(), BorderLayout.PAGE_START);
...
}
public class PageStart{
public static JPanel Panel(){
JPanel panel = new JPanel();
FlowLayout pagestart = new FlowLayout(FlowLayout.RIGHT);
panel.setLayout(pagestart);
panel.add(MinimizeButton());
panel.add(ResizeButton());
panel.add(QuitButton());
}
public static JButton MinimizeButton(){
JButton button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// I Should be able to reach Loginwards here.
}
});
return button;
}
最佳答案
MinimizeButton
是一个静态方法,因此将 Loginwards 实例作为参数传递,然后在监听器中使用它:
public static JButton MinimizeButton(Loginwards loginwards){
JButton button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Invoke whatever you need on Loginwards...
loginwards.doSomething();
}
});
return button;
}
顺便说一句,方法名称应以小写字母开头...请参阅 naming conventions for Java
关于Java子对象运行父对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52203818/