nameapplet3buttons.java
来自「Java the UML Way 书中所有源码」· Java 代码 · 共 59 行
JAVA
59 行
/*
* NameApplet3Buttons.java E.L. 2001-08-18
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NameApplet3Buttons extends JApplet {
private Container guiContainer;
private JTextField nameField = new JTextField(20);
private JLabel greeting = new JLabel();
public void init() {
guiContainer = getContentPane();
guiContainer.setLayout(new FlowLayout());
JLabel nameLabel = new JLabel("What's your name?");
guiContainer.add(nameLabel);
guiContainer.add(nameField);
/*
* Creates three buttons with color according to the text on the buttons.
* Puts all the buttons in the guiContainer.
*/
JButton buttonRed = new JButton("Red");
buttonRed.setBackground(Color.red);
guiContainer.add(buttonRed);
JButton buttonBlue = new JButton("Blue");
buttonBlue.setBackground(Color.blue);
guiContainer.add(buttonBlue);
JButton buttonCyan = new JButton("Cyan");
buttonCyan.setBackground(Color.cyan);
guiContainer.add(buttonCyan);
/*
* Creates a listener and links all the buttons to the same listener.
*/
ButtonListener theButtonListener = new ButtonListener();
buttonRed.addActionListener(theButtonListener);
buttonBlue.addActionListener(theButtonListener);
buttonCyan.addActionListener(theButtonListener);
guiContainer.add(greeting);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String colorName = event.getActionCommand();
Color color;
if (colorName.equals("Red")) color = Color.red;
else if (colorName.equals("Blue")) color = Color.blue;
else color = Color.cyan;
greeting.setForeground(color);
String name = nameField.getText();
greeting.setText("Hallo, " + name + "!");
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?