Java编写一个有两个文本框和一个按钮的应用程序在一个文本框输入一个字符串按回车或单击按钮,

2024年12月04日 23:51
有1个网友回答
网友(1):

这段应该符合你的要求

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import sun.io.ByteToCharConverter;
import sun.io.CharToByteConverter;

public class Test extends JFrame implements ActionListener {
JButton btn = new JButton("ok");
JTextField tf1 = new JTextField(20);
JTextField tf2 = new JTextField(20);

public Test() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pn = new JPanel();
pn.add(tf1);
tf1.addActionListener(this);
pn.add(tf2);
this.getContentPane().add(pn, BorderLayout.CENTER);
this.getContentPane().add(btn, BorderLayout.SOUTH);
btn.addActionListener(this);
this.pack();
this.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
String str=tf1.getText();
tf2.setText("");
try {
ByteToCharConverter converter = ByteToCharConverter
.getConverter("GB2312");
CharToByteConverter converter1 = CharToByteConverter
.getConverter("GB2312");
byte[] b =str.getBytes();
char[] c = new char[4];
c = converter.convertAll(b);
for (int i = 0; i < c.length; i++) {
tf2.setText(tf2.getText()+"\\u" + Integer.toHexString(c[i]));
}
} catch (Exception ex) {
ex.printStackTrace();
}

}

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