用java JFrame写一个背单词程序
时间: 2024-05-18 16:15:24 浏览: 84
背单词_java_src.rar_JAVA 背单词_单词软件_背单词
好的,我可以给你提供一个简单的 Java JFrame 背单词程序的代码示例,具体实现方式如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Vocabulary extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JButton btnShowWord;
private JLabel lblWord;
private JLabel lblMeaning;
// 单词列表
private String[] words = { "apple", "banana", "cherry", "date", "elderberry" };
// 对应的单词释义
private String[] meanings = { "苹果", "香蕉", "樱桃", "枣", "接骨木果" };
// 当前显示的单词索引
private int currentIndex = 0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Vocabulary frame = new Vocabulary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Vocabulary() {
setTitle("背单词程序");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 200);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel buttonPanel = new JPanel();
contentPane.add(buttonPanel, BorderLayout.SOUTH);
btnShowWord = new JButton("显示单词");
btnShowWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showNextWord();
}
});
buttonPanel.add(btnShowWord);
JPanel wordPanel = new JPanel();
contentPane.add(wordPanel, BorderLayout.CENTER);
wordPanel.setLayout(new GridLayout(2, 1, 0, 0));
lblWord = new JLabel(words[currentIndex]);
lblWord.setFont(new Font("宋体", Font.PLAIN, 30));
lblWord.setHorizontalAlignment(SwingConstants.CENTER);
wordPanel.add(lblWord);
lblMeaning = new JLabel(meanings[currentIndex]);
lblMeaning.setFont(new Font("宋体", Font.PLAIN, 20));
lblMeaning.setHorizontalAlignment(SwingConstants.CENTER);
wordPanel.add(lblMeaning);
}
// 显示下一个单词
private void showNextWord() {
currentIndex = (currentIndex + 1) % words.length;
lblWord.setText(words[currentIndex]);
lblMeaning.setText(meanings[currentIndex]);
}
}
```
程序界面如下:
![背单词程序界面](https://img-blog.csdnimg.cn/2021092415272737.png)
该程序会在程序界面中显示一个单词和对应的释义,点击“显示单词”按钮可以切换到下一个单词。你可以根据自己的需求进行修改和完善。
阅读全文