帮我写一个代码,使用菜单栏、工具栏、布局管理器、按钮、表格等多种Java图形界面组件。写一个关于解决吃饭选择困难症,随机生成饭式或者菜式或者小食
时间: 2023-12-29 19:02:23 浏览: 75
好的,下面是一个简单的 Java 图形界面程序,可以随机生成饭菜或小食的名称:
```java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class ChooseFoodFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private static final String[] TYPES = { "饭菜", "小食" };
private static final String[] FOODS = { "炒饭", "炸鸡", "沙拉", "披萨", "汉堡", "烤肉", "寿司", "火锅", "烤鱼", "鲍鱼粥" };
private static final String[] SNACKS = { "薯条", "卤蛋", "饺子", "煎饼果子", "烤串", "煎饼", "豆腐脑", "肉夹馍", "烤麸", "烤鸭脖" };
private static final String[] COLUMN_NAMES = { "类型", "名称" };
private JButton chooseButton;
private JTable foodTable;
private DefaultTableModel tableModel;
public ChooseFoodFrame() {
setTitle("选择今天的吃食");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
Container contentPane = getContentPane();
// 创建工具栏
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.add(new JLabel("今天吃什么?"));
contentPane.add(toolBar, BorderLayout.PAGE_START);
// 创建表格面板
JPanel tablePanel = new JPanel(new GridLayout(1, 1));
tablePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
tableModel = new DefaultTableModel(COLUMN_NAMES, 0);
foodTable = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(foodTable);
tablePanel.add(scrollPane);
contentPane.add(tablePanel, BorderLayout.CENTER);
// 创建底部面板
JPanel bottomPanel = new JPanel(new GridLayout(1, 1));
bottomPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
chooseButton = new JButton("随机选择");
chooseButton.addActionListener(this);
bottomPanel.add(chooseButton);
contentPane.add(bottomPanel, BorderLayout.PAGE_END);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == chooseButton) {
Random random = new Random();
String type = TYPES[random.nextInt(TYPES.length)];
String food = "";
if (type.equals("饭菜")) {
food = FOODS[random.nextInt(FOODS.length)];
} else if (type.equals("小食")) {
food = SNACKS[random.nextInt(SNACKS.length)];
}
String[] rowData = { type, food };
tableModel.addRow(rowData);
}
}
public static void main(String[] args) {
new ChooseFoodFrame();
}
}
```
这个程序使用了菜单栏、工具栏、表格和按钮等多种 Java 图形界面组件。可以通过点击“随机选择”按钮来随机生成饭菜或小食的名称,并将结果显示在表格中。注意,这个程序只是一个简单的示例,实际使用时可能需要更复杂的逻辑和更多的用户界面设计。
阅读全文