程序修改如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JFrame1 extends JFrame implements ActionListener {
private JLabel textLabel;
private JRadioButton italicButton;
private JRadioButton boldButton;
public JFrame1() {
super("Font Changer");
setSize(400, 300);
// 创建面板和标签
JPanel panel = new JPanel(new BorderLayout());
textLabel = new JLabel("Hello World!", JLabel.CENTER);
panel.add(textLabel, BorderLayout.CENTER);
// 创建按钮组和单选按钮,并添加到面板中
ButtonGroup buttonGroup = new ButtonGroup();
italicButton = new JRadioButton("ITALIC");
italicButton.addActionListener(this);
buttonGroup.add(italicButton);
boldButton = new JRadioButton("BOLD");
boldButton.addActionListener(this);
buttonGroup.add(boldButton);
JPanel buttonPanel = new JPanel();
buttonPanel.add(italicButton);
buttonPanel.add(boldButton);
panel.add(buttonPanel, BorderLayout.SOUTH);
// 将面板添加到窗口中,并设置窗口居中显示
add(panel);
setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
// 根据单选按钮的状态设置标签字体样式
Font font = textLabel.getFont();
if (italicButton.isSelected()) {
font = font.deriveFont(Font.ITALIC);
} else if (boldButton.isSelected()) {
font = font.deriveFont(Font.BOLD);
} else {
font = font.deriveFont(Font.PLAIN);
}
textLabel.setFont(font);
}
public static void main(String[] args) {
JFrame1 fontChanger = new JFrame1();
fontChanger.setVisible(true);
}
}
