哪種更好,爲什麼? 在我沒有受過教育的意見中,最好將它們放在單獨的文件中,因爲如果您有10個按鈕,5個組合框和一個或兩個在一個文件中具有所有這些類的列表將變得雜亂無章。我是否正確地認爲?爲什麼你會選擇一個呢?把事件監聽器放在哪裏?
SimpleGUI.java:
public class simpleGUI extends JFrame {
public JButton button;
public JLabel label;
public simpleGUI() {
Container contentPane = getContentPane();
JPanel panel = new JPanel();
label = new JLabel("123abc");
button = new JButton("click me");
simpleEventListener c = new simpleEventListener();
c.setParams(label);
button.addActionListener(c);
panel.add(button);
panel.add(label);
contentPane.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setTitle("simpleGUI");
setVisible(true);
}
public static void main(String[]args) {
JFrame frame = new simpleGUI();
}
}
simpleEventListener.java:
public class simpleEventListener implements ActionListener {
private JLabel label;
public void actionPerformed(ActionEvent e) {
label.setText("Hello World!");
}
public void setParams(JLabel label) {
this.label = label;
}
}
或:
public class simpleGUI extends JFrame {
public JButton button;
public JLabel label;
public simpleGUI() {
Container contentPane = getContentPane();
JPanel panel = new JPanel();
label = new JLabel("123abc");
button = new JButton("click me");
simpleEventListener c = new simpleEventListener();
button.addActionListener(c);
panel.add(button);
panel.add(label);
contentPane.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setTitle("simpleGUI");
setVisible(true);
}
public class simpleEventListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Hello World!");
}
}
public static void main(String[]args) {
JFrame frame = new simpleGUI();
}
}