对课本中的一个例子,稍加拓展,目的是为了更好的理解一些组件的应用,该小软件实现的是,输入一个字符串,就可以把你输入的字符串转换为相应的Unicode码输出,另外,为了练习对话框,增加了一个简单的对话框应用,源代码如下: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class QueryFrame extends JFrame implements ActionListener { /** * author:xy */ private static final long serialVersionUID = 1L; private JTextField text_char,text_uni; private JButton btn_char,btn_uni; private MessageJDialog jdlg; private JButton btn_love; private JTextField text_love; public QueryFrame() { super("Unicode 字符转换器"); this.setBounds(280,100,403,150); this.setResizable(true); this.setBackground(Color.RED); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.getContentPane().setLayout(new FlowLayout(FlowLayout.RIGHT)); this.getContentPane().add(new JLabel("字符串")); text_char=new JTextField(15); this.getContentPane().add(text_char); btn_uni=new JButton("查询Unicode码"); this.getContentPane().add(btn_uni); btn_uni.addActionListener(this); this.getContentPane().add(new JLabel("Unicode码")); text_uni=new JTextField(15); this.getContentPane().add(text_uni); btn_char=new JButton("查询字符 "); this.getContentPane().add(btn_char); btn_char.addActionListener(this); this.getContentPane().add(new JLabel("对TA说的话:")); text_love=new JTextField(15); this.getContentPane().add(text_love); btn_love=new JButton(" 发送 "); this.getContentPane().add(btn_love); btn_love.addActionListener(this); this.setVisible(true); } public class MessageJDialog extends JDialog { private static final long serialVersionUID = 1L; JFrame jframe; JLabel jlabel; public MessageJDialog(JFrame jframe) { super(jframe,"提示",true); this.jframe=jframe; this.setSize(300,100); jlabel=new JLabel("",JLabel.CENTER); this.getContentPane().add(jlabel); this.setDefaultCloseOperation(HIDE_ON_CLOSE); } public void show(String message) { jlabel.setText(message); this.setLocation(jframe.getX()+10, jframe.getY()+10); this.setVisible(true); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn_uni) { String str=text_char.getText(); int tmp; String sUni=new String(); for(int i=0;i<str.length();i++) { tmp=(int)str.charAt(i);//将字符转换成Unicode sUni+=String.valueOf(tmp)+" ";//将整形转换成字符串存储到字符串对象中 } text_uni.setText(sUni); } if(e.getSource()==btn_char) { int uni=Integer.parseInt(text_uni.getText());//将字符串转换成整形 text_char.setText(""+(char)uni);//将整形转换成字符 } if(e.getSource()==btn_love) { jdlg=new MessageJDialog(this); if(!text_love.getText().isEmpty()) jdlg.show(text_love.getText()); } } public static void main(String arg[]) { new QueryFrame(); } }