日期:2014-05-20  浏览次数:20748 次

[玩一玩]给命令行做一个GUI,JAVA版
在主页上看到,C#区有大牛给DOS的CMD做了个GUI,挺好玩的,我也动手做一个
C#贴:http://topic.csdn.net/u/20120630/19/C3D46E45-72AB-4278-9C87-EB6B88038B95.html

程序相对来说很简单,(连释放都没有管,直接exit了,太偷懒了...)

效果图:




源代码:
ConsoleGUI.java:

package consoleGUI;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultCaret;

public class ConsoleGUI extends JFrame {

private static final long serialVersionUID = 1L;

private JTextField tf_cmd;
private JButton btn_run;
private JTextArea ta_result;

private Process process;
private PrintWriter out;

public ConsoleGUI() {
// 窗体大小
this.setPreferredSize(new Dimension(500,500));
this.setTitle("命令行GUI");

// 命令框及按钮
TitledBorder titledBorder = new TitledBorder("Command input");
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(titledBorder);

topPanel.add(tf_cmd = new JTextField(),BorderLayout.CENTER);
topPanel.add(btn_run = new JButton("执行"),BorderLayout.EAST);

this.getContentPane().add(topPanel,BorderLayout.NORTH);

// 显示结果
JScrollPane resultPanel = new JScrollPane(ta_result = new JTextArea());
this.getContentPane().add(resultPanel);
((DefaultCaret)ta_result.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


// 启动一个CMD
try {
this.process = Runtime.getRuntime().exec("cmd");
// 获取CMD的输出流
this.out = new PrintWriter(process.getOutputStream());
// 将CMD的输入流绑定到显示框中
new ConsoleIntercepter(ta_result, process.getInputStream()).start();
new ConsoleIntercepter(ta_result, process.getErrorStream()).start();
} catch (IOException e) {
e.printStackTrace();
}

// 执行按钮 将命令发送给CMD
this.btn_run.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(tf_cmd.getText().equals(""))
return;

ta_result.setText("");
out.println(tf_cmd.getText());
out.flush();
}
});

// 命令框中按下回车键的事件
this.tf_cmd.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
btn_run.doClick();
tf_cmd.setText("");
}
}
});
}

// 显示窗体
public void showFrame() {
this.pack();
this.setVisible(true);
}


public static void main(String[] args) {