67,513
社区成员
发帖
与我相关
我的任务
分享
package com.gui;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class MyDOS extends JFrame {
/**
*
*/
private static final long serialVersionUID = -5418344602348249043L;
private JPanel pup = new JPanel();
private JPanel pdown = new JPanel();
private JTextField txtCommand = new JTextField(45);
private JTextArea txtContent = new JTextArea();
private JButton btnExec = new JButton("Execute");
public MyDOS() {
// 指定框架的布局管理器
setLayout(new BorderLayout());
// 设置文本框,文本域字体
txtCommand.setFont(new Font("", Font.BOLD, 13));
txtContent.setFont(new Font("", Font.BOLD, 13));
// 指定面板的布局
pup.setLayout(new BorderLayout());
pdown.setLayout(new FlowLayout());
// 将文本域添加导面板中
pup.add(txtContent);
// 为文本域添加滚动条
pup.add(new JScrollPane(txtContent));
// 将文本框,按钮添加到面板中
pdown.add(txtCommand);
pdown.add(btnExec);
// 添加面板到框架中
this.add(pup, BorderLayout.CENTER);
this.add(pdown, BorderLayout.SOUTH);
// 设置事件
// 添加按钮事件
btnExec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s;
// 获取文本框中的命令
String command = txtCommand.getText().trim();
Process process;
try {
process = Runtime.getRuntime().exec("cmd /c " + command);
// 截获被调用程序的DOS运行窗口的标准输出
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while ((s = br.readLine()) != null)
txtContent.append(s + "\r\n");
process.waitFor();
txtCommand.setText("");
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
});
// 添加键盘Enter事件
txtCommand.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// 当按下回车时
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
String s;
// 获取文本框中的命令
String command = txtCommand.getText().trim();
Process process;
try {
process = Runtime.getRuntime()
.exec("cmd /c " + command);
// 截获被调用程序的DOS运行窗口的标准输出
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while ((s = br.readLine()) != null)
txtContent.append(s + "\r\n");
process.waitFor();
txtCommand.setText("");
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
});
}
public static void main(String[] args) {
MyDOS frame = new MyDOS();
frame.setTitle("MyDOS");
frame.setSize(666, 444);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}