Java中如何在窗口中加入字体样式设置菜单,字体包括宋体、正楷、草书等等,请给出程序代码
时间: 2024-01-22 18:21:28 浏览: 23
以下是一个简单的Java程序,可以在窗口中加入字体样式设置菜单,并且支持选择宋体、楷体和草书三种字体:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FontMenuExample extends JFrame implements ActionListener {
private JTextArea textArea;
private JMenuBar menuBar;
private JMenu fontMenu;
private JMenuItem songMenuItem, kaiMenuItem, caoMenuItem;
public FontMenuExample() {
super("Font Menu Example");
// Create a text area
textArea = new JTextArea();
textArea.setEditable(true);
textArea.setFont(new Font("宋体", Font.PLAIN, 16));
// Create a menu bar
menuBar = new JMenuBar();
// Create a font menu
fontMenu = new JMenu("字体");
songMenuItem = new JMenuItem("宋体");
kaiMenuItem = new JMenuItem("楷体");
caoMenuItem = new JMenuItem("草书");
songMenuItem.addActionListener(this);
kaiMenuItem.addActionListener(this);
caoMenuItem.addActionListener(this);
fontMenu.add(songMenuItem);
fontMenu.add(kaiMenuItem);
fontMenu.add(caoMenuItem);
// Add the font menu to the menu bar
menuBar.add(fontMenu);
// Set the menu bar for the frame
setJMenuBar(menuBar);
// Add the text area to the frame
add(new JScrollPane(textArea));
// Set the size and visibility of the frame
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == songMenuItem) {
textArea.setFont(new Font("宋体", Font.PLAIN, 16));
} else if (e.getSource() == kaiMenuItem) {
textArea.setFont(new Font("楷体", Font.PLAIN, 16));
} else if (e.getSource() == caoMenuItem) {
textArea.setFont(new Font("草书", Font.PLAIN, 16));
}
}
public static void main(String[] args) {
new FontMenuExample();
}
}
```
在这个程序中,我们首先创建了一个`JTextArea`对象作为文本区域,然后创建了一个`JMenuBar`对象作为菜单栏。接着,我们创建了一个`JMenu`对象作为字体菜单,并在其中添加了三个`JMenuItem`对象,分别对应宋体、楷体和草书三种字体。我们还实现了`ActionListener`接口,以便在用户选择不同的字体时能够响应事件并设置相应的字体。最后,我们将菜单栏添加到窗口上,将文本区域添加到窗口上,并设置窗口的大小和可见性。