创建 GUI
Applet 可以很容易地用于创建 GUI。它们就像一个 Container
,并且有一个 add()
方法,可以接受任何 awt
或 swing
组件。
public class MyGUIApplet extends JApplet{
private JPanel panel;
private JButton button;
private JComboBox<String> cmbBox;
private JTextField textField;
@Override
public void init(){
panel = new JPanel();
button = new JButton("ClickMe!");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
if(((String)cmbBox.getSelectedItem()).equals("greet")) {
JOptionPane.showMessageDialog(null,"Hello " + textField.getText());
} else {
JOptionPane.showMessageDialog(null,textField.getText() + " stinks!");
}
}
});
cmbBox = new JComboBox<>(new String[]{"greet", "offend"});
textField = new JTextField("John Doe");
panel.add(cmbBox);
panel.add(textField);
panel.add(button);
add(panel);
}
}