1.13

package com.example.demo;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.util.Enumeration;

public class Gui extends JFrame {

private JPanel root;
private JLabel label1, label2;
private JTextField text1, textrs;
private JButton zh, en;

public Gui() {
super("中英翻译器");
root = new JPanel(new GridBagLayout());
setContentPane(root);
InitGlobalFont(new Font("仿宋", Font.PLAIN, 16));

GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5); // 添加一些内边距

// 左侧部分
label1 = new JLabel("输入: ");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END; // 标签靠右对齐
root.add(label1, gbc);

text1 = new JTextField();
text1.setPreferredSize(new Dimension(300, 30)); // 设置输入框的首选大小
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 2; // 占据两列
gbc.fill = GridBagConstraints.HORIZONTAL; // 水平填充
root.add(text1, gbc);

// 按钮
zh = new JButton("中译英");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1; // 占据一列
gbc.fill = GridBagConstraints.NONE; // 不填充
gbc.anchor = GridBagConstraints.CENTER; // 按钮居中对齐
root.add(zh, gbc);

en = new JButton("英译中");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1; // 占据一列
gbc.fill = GridBagConstraints.NONE; // 不填充
gbc.anchor = GridBagConstraints.CENTER; // 按钮居中对齐
root.add(en, gbc);

// 右侧部分
label2 = new JLabel("翻译: ");
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_END; // 标签靠右对齐
root.add(label2, gbc);

textrs = new JTextField();
textrs.setEditable(false); // 设置为不可编辑
textrs.setPreferredSize(new Dimension(300, 30)); // 设置结果框的首选大小
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2; // 占据两列
gbc.fill = GridBagConstraints.HORIZONTAL; // 水平填充
root.add(textrs, gbc);

// 按钮事件
zh.addActionListener(e -> {
String rs = DemoApplication.zhToen(text1.getText());
textrs.setText(rs);
});

en.addActionListener(e -> {
String rs = DemoApplication.enTozh(text1.getText());
textrs.setText(rs);
});

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(400, 300, 600, 300);
setVisible(true);
}

private static void InitGlobalFont(Font font) {
FontUIResource fontRes = new FontUIResource(font);
for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements(); ) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
UIManager.put(key, fontRes);
}
}
}

public static void main(String[] args) {
new Gui();
}
}

posted @ 2025-01-13 21:57  catsahsy  阅读(11)  评论(0)    收藏  举报