设有一批英文单词存放在一个数组中,编制一个图形界面程序浏览单词。在界面中安排一个标签显示单词,另有“上一个”、“下一个”两个按钮实现单词的前后翻动。用Java写
时间: 2024-05-04 20:19:06 浏览: 7
以下是一个简单的Java程序,可以实现浏览英文单词的功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WordBrowser extends JFrame implements ActionListener {
private JLabel wordLabel;
private JButton prevButton;
private JButton nextButton;
private String[] words;
private int currentIndex;
public WordBrowser(String[] words) {
this.words = words;
this.currentIndex = 0;
wordLabel = new JLabel(words[currentIndex]);
wordLabel.setHorizontalAlignment(JLabel.CENTER);
wordLabel.setFont(new Font("Arial", Font.BOLD, 24));
prevButton = new JButton("上一个");
prevButton.addActionListener(this);
nextButton = new JButton("下一个");
nextButton.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
buttonPanel.add(prevButton);
buttonPanel.add(nextButton);
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.add(wordLabel, BorderLayout.CENTER);
contentPanel.add(buttonPanel, BorderLayout.SOUTH);
setContentPane(contentPanel);
setTitle("单词浏览器");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == prevButton) {
currentIndex--;
if (currentIndex < 0) {
currentIndex = words.length - 1;
}
wordLabel.setText(words[currentIndex]);
} else if (e.getSource() == nextButton) {
currentIndex++;
if (currentIndex >= words.length) {
currentIndex = 0;
}
wordLabel.setText(words[currentIndex]);
}
}
public static void main(String[] args) {
String[] words = {"apple", "banana", "cherry", "durian", "elderberry"};
WordBrowser browser = new WordBrowser(words);
}
}
```
在这个程序中,我们使用了Java Swing库来创建图形界面。程序的主要组件是一个JLabel和两个JButton。JLabel用来显示当前单词,JButton用来实现前后翻页。我们在程序的构造函数中初始化了这些组件,并将它们添加到一个JPanel中,最终将该面板设置为窗口的内容面板。
在按钮的事件处理函数中,我们实现了单词的前后翻页功能。通过修改currentIndex变量的值,我们可以得到当前的单词索引,然后将相应的单词显示在标签中。如果当前的单词已经是第一个或最后一个单词,我们需要将索引值调整到数组的另一端。
在main函数中,我们创建了一个包含一些测试单词的WordBrowser对象。运行程序后,我们可以在窗口中看到第一个单词,并通过点击按钮来浏览其他单词。