📄 buttoneventsdemo.java
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Demonstrates event-handling for radio buttons. This class extends
* class {@link @JPanel}.
*
* @author author name
* @version 1.0.0
*/
public class ButtonEventsDemo extends JPanel {
private JRadioButton buttonOne;
private JRadioButton buttonTwo;
private JRadioButton buttonThree;
private JLabel label;
/**
* Creates a window.
*
* @param args not used.
*/
public static void main(String[] args) {
JFrame frame = new JFrame("ButtonEventsDemo");
frame.setContentPane(new ButtonEventsDemo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
/**
* Creates the components.
*/
public ButtonEventsDemo() {
setBackground(Color.white);
// Creates the components
buttonOne = new JRadioButton("One", true);
buttonTwo = new JRadioButton("Two");
buttonThree = new JRadioButton("Three");
label = new JLabel(buttonOne.getText());
label.setFont(new Font("Serif", Font.BOLD, 42));
label.setHorizontalAlignment(JLabel.CENTER);
// Group the radio buttons
ButtonGroup group = new ButtonGroup();
group.add(buttonOne);
group.add(buttonTwo);
group.add(buttonThree);
// Change the buttons colors
buttonOne.setBackground(Color.white);
buttonTwo.setBackground(Color.white);
buttonThree.setBackground(Color.white);
// Register the listeners for the radio buttons.
buttonOne.addActionListener(new ListenerOne());
buttonTwo.addActionListener(new ListenerTwo());
buttonThree.addActionListener(new ListenerThree());
// Add the radio buttons to a panel
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
panel.add(buttonOne);
panel.add(buttonTwo);
panel.add(buttonThree);
// Create the layout
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(label, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEtchedBorder());
label.setBorder(BorderFactory.createLoweredBevelBorder());
}
/**
* This inner class handles events associated with radio
* button "One".
*/
class ListenerOne implements ActionListener {
/**
* Changes the text of the label.
*
* @param event the event object.
*/
public void actionPerformed(ActionEvent event) {
label.setText(buttonOne.getText());
}
}
/**
* This inner class handles events associated with radio
* button "Two".
*/
class ListenerTwo implements ActionListener {
/**
* Changes the text of the label.
*
* @param event the event object.
*/
public void actionPerformed(ActionEvent event) {
label.setText(buttonTwo.getText());
}
}
/**
* This inner class handles events associated with radio
* button "Three".
*/
class ListenerThree implements ActionListener {
/**
* Changes the text of the label.
*
* @param event the event object.
*/
public void actionPerformed(ActionEvent event) {
label.setText(buttonThree.getText());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -