我还是Java Swing的新手,我们已经为一个班学习了它,我这样做是为了一个小项目。
因此,当被限制在1个java文件中时,GUI就是这样的(没有规范和设计(。然而,由于代码的长度,我的文件变得非常混乱,并且有很多不必要的变量名,因为我不能在每个屏幕上再次使用相同的变量名。我在学校学习Java Swing已经3个月了,但我现在才遇到这个问题。我想知道如何分离GUI文件(即Screen1GUI.java、Screen2GUI.java和Screen3GUI.java,…(,但遗憾的是,我们从未解决过这个问题,而且我似乎找不到合适的单词来在线搜索。
public JLayeredPane layeredPane;
private JPanel Screen1, Screen2, Screen3;
private JButton switch1, switch2;
public MainGUI() {
// other code
Screen1 = new JPanel();
// Screen1 GUI
layeredPane.add(Screen1, "Screen 1");
switch.addActionListener((ActionEvent a) -> {
switchScreens(Screen2);
});
Screen1.add(switch1);
Screen2 = new JPanel();
// Screen2 GUI
layeredPane.add(Screen2, "Screen 2");
switch2.addActionListener((ActionEvent b) -> {
switchScreens(Screen3);
});
Screen2.add(switch2);
Screen3 = new JPanel();
// Screen3 GUI
layeredPane.add(Screen3, "Screen 3");
CardLayout screens = (CardLayout) layeredPane.getLayout();
screens.show(layeredPane, "Screen 1");
// other code
}
public void switchScreens(JPanel screen) {
layeredPane.removeAll();
layeredPane.add(screen);
layeredPane.repaint();
layeredPane.revalidate();
}
要将每个swing对象分离为自己的类,您应该能够简单地创建一个扩展JPanel的新类,例如
public class Screen1GUI extends JPanel {
public Screen1GUI(){
super();
}
}
为了使它更有组织性,您可能可以抽象类,以考虑类似的属性,如屏幕名称和切换按钮
public class Screen extends JPanel {
private JButton switchButton;
private String title;
public Screen(){
super();
}
public Screen(String title){
this();
this.title=title;
}
public void setNext(JPanel next){
if(switchButton!=null){
this.remove(switchButton);
}
if(next!=null){
switchButton=new Button("next");
switchButton.addActionListener(e->switchScreens(next));
}
}
public String getTitle(){
return title;
}
private void switchScreens(JPanel panel){
Component parent = getParent();
parent.removeAll();
parent.add(screen);
parent.repaint();
parent.revalidate();
}
}
然后在您的MainGUI方法中
Screen Screen1;
Screen Screen2;
Screen Screen3;
JLayeredPane layeredPane;
public void MainGUI(){
Screen1 = new Screen("Screen1");
Screen2 = new Screen("Screen2");
Screen3 = new Screen("Screen3");
Screen1.setNext(Screen2);
Screen2.setNext(Screen3);
addAll(Screen1,Screen2,Screen3);
}
public void addAll(Screen...screens){
for(Screen screen : screens){
layeredPane.add(screen,screen.getTitle());
}
}