I have a main class File
and another extend class File 2
how can i access a textfield declared in File with awt and Swing to the extended class File2 ?
main class:-
import java.util.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FileReceive extends FileReceiveUtil {
int msgIndex = 1;
Statement s;
public static File f;
public static String phoneNo, phoneNoLo, sk;
public static String str = "";
public static String path = "";
public String ran, ran11;
public String mes, sharedString;
FileReceive() throws Exception {
super("COM4");
}
#Override
public void processSMS(String str) throws Exception {
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("File Receive");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel nameId = new JLabel("Enter Destination Path");
JButton browseb = new JButton("Browse");
JLabel bodyTempId = new JLabel("Path : ");
final JTextField jtf = new JTextField(" ");
JButton sendB = new JButton("Receive");
panel.add(nameId);
panel.add(browseb);
panel.add(bodyTempId);
panel.add(jtf);
panel.add(sendB);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this()
browseb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jf = new JFileChooser();
String str1 = "";
int m = jf.showOpenDialog(null);
if (m == JFileChooser.APPROVE_OPTION) {
f = jf.getSelectedFile();
str = f.getPath();
path = f.getAbsolutePath();
jtf.setText(path);
}
}
});
sendB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FileReceiveUtil util = null;
try {
util = new FileReceive();
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList al = new ArrayList();
try {
util.startReceive(al, 10);
} catch (Exception ex) {
Logger.getLogger(FileReceive.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Extended class :-
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JTextField;
public abstract class FileReceiveUtil implements Runnable {
private static int responseCode = -1;
private static String userCredentials = null;
private static String cookie = null;
private static String site = null;
private static String actionStr = null;
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private OutputStream outputStream;
private String strPortName;
private InputStream inputStream;
private boolean boolKeepReceiving = true;
private Thread threadRX;
private ArrayList alSMSStore;
private int intDelay;
public FileReceiveUtil(String strPortName) throws Exception {
this.strPortName = strPortName;
initCommPort();
}
private void initCommPort() throws Exception {
boolean boolPortOK = false;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equalsIgnoreCase(strPortName)) {
this.serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.notifyOnDataAvailable(true);
serialPort.setSerialPortParams(230400,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
boolPortOK = true;
break;
}
}
}
if (!boolPortOK) {
throw new Exception("Port " + strPortName + " does not exist!");
}
}
private String readSMS() throws Exception {
StringBuffer sb = new StringBuffer();
sb.append(writeATCmd());
return sb.toString();
}
private String writeATCmd() throws Exception {
//Thread.sleep(2000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[1];
// Thread.sleep(10);
int ch = inputStream.read(data);
//System.out.println(x);
bos.write(data, 0, 1);
byte[] bytes = bos.toByteArray();
File someFile = new File("D:\\yadhu.txt");
FileOutputStream fos = new FileOutputStream(someFile,true);
fos.write(bytes);
fos.flush();
fos.close();
String str = bytes.toString();
System.out.println("Data : "+ str);
return str;
}
private void startReceivingSMS() throws Exception {
final String ERROR = "ERROR";
while (boolKeepReceiving) {
Thread.sleep(intDelay);
try {
System.out.println(" File recieved ");
String str = readSMS();
} catch (Throwable t) {
System.out.println("ERROR RECEIVING MSG");
t.printStackTrace();
}
}
}
final public void startReceive(ArrayList alSMSStore, int intDelay) throws Exception {
this.alSMSStore = alSMSStore;
this.intDelay = intDelay;
threadRX = new Thread(this);
threadRX.start();
}
final public void run() {
try {
startReceivingSMS();
} catch (Throwable t) {
t.printStackTrace();
}
}
final public void stopReceivingSMS() {
this.boolKeepReceiving = false;
}
public ArrayList getReceivedMessages() {
return this.alSMSStore;
}
private static void exit(String errorMsg) {
System.err.println(errorMsg);
System.exit(1);
}
public abstract void processSMS(String message) throws Exception;
}
i want " File someFile = new File("D:\yadhu.txt"); " to change this and add file name from the jtextfield on gui
please help
make the JTextField global in the class instead of a local function item.
Related
I'm rewriting an applet I have, but when it loads it's giving me a runtime exception.
The exception is
Exception in thread "main" java.lang.NoSuchMethodError: ClientSettings: method <
init>()V not found
at RunClient.<init>(RunClient.java:41)
at RunClient.main(RunClient.java:63)
Here is RunClient:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
public class RunClient extends Applet implements ActionListener {
private Robot robot;
private static final long serialVersionUID = 1L;
public static Properties params = new Properties();
public JFrame mainFrame;
public JPanel mainPane = new JPanel();
public static String[] data;
public String mainurl = getParameter("ip");
public int lang = 0;
public String frameName = getParameter("servername");
public JPanel totalPanel;
private JMenuBar menuBar = new JMenuBar();
private int capNum;
private FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File arg0, String arg1) {
if (arg0.getName().equals("images") && arg1.endsWith("png")) {
return true;
}
return false;
}
};
public static final Object[][] JMENU_BUTTONS = new Object[][]{{"File", new JMenuItem("New Client"), new JSeparator(), new JMenuItem("Exit")}, {"Guides", new JMenuItem("Getting Started"), new JMenuItem("Fighting Monsters"), new JMenuItem("Money Making")}, {"Links", new JMenuItem("Wiki"), new JMenuItem("Forums"), new JMenuItem("Youtube"), new JMenuItem("Donate")}, {"Tools", new JMenuItem("Take a screenshot")}};
public String[] getLoaderParameters() {
return new String[]{getParameter("servername"), getParameter("ip"), getParameter("port")};
}
public static void main(String[] strings) {
data = getLoaderParameters();
new ClientSettings(data);
RunClient runclient = new RunClient();
runclient.doFrame();
}
public RunClient() {
try {
loadCaptureAmts();
robot = new Robot();
} catch(Exception e) {
e.printStackTrace();
}
}
private void loadCaptureAmts() {
capNum = new File("./images/").listFiles(filter).length;
}
public void init() {
doApplet();
}
void doApplet() {
try {
readVars();
startClient();
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void doFrame() {
try {
readVars();
openFrame();
startClient();
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void readVars() throws IOException {
params.put("cabbase", "g.cab");
params.put("java_arguments", "-Xmx1024m -Dsun.java2d.noddraw=true");
params.put("colourid", "0");
params.put("worldid", "16");
params.put("lobbyid", "15");
params.put("demoid", "0");
params.put("demoaddress", "");
params.put("modewhere", "0");
params.put("modewhat", "0");
params.put("lang", "0");
params.put("objecttag", "0");
params.put("js", "1");
params.put("game", "0");
params.put("affid", "0");
params.put("advert", "1");
params.put("settings", "wwGlrZHF5gJcZl7tf7KSRh0MZLhiU0gI0xDX6DwZ-Qk");
params.put("country", "0");
params.put("haveie6", "0");
params.put("havefirefox", "1");
params.put("cookieprefix", "");
params.put("cookiehost", "127.0.0.1");
params.put("cachesubdirid", "0");
params.put("crashurl", "");
params.put("unsignedurl", "");
params.put("sitesettings_member", "1");
params.put("frombilling", "false");
params.put("sskey", "");
params.put("force64mb", "false");
params.put("worldflags", "8");
params.put("lobbyaddress", mainurl);
}
public void openFrame() {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
mainPane.setLayout(new BorderLayout());
mainPane.add(this);
mainPane.setPreferredSize(new Dimension(765, 503));
totalPanel = new JPanel();
totalPanel.setPreferredSize(new Dimension(765, 503));
totalPanel.setLayout(new BorderLayout());
totalPanel.add(mainPane, BorderLayout.CENTER);
mainFrame = new JFrame(frameName);
mainFrame.setLayout(new BorderLayout());
mainFrame.getContentPane().add(totalPanel, BorderLayout.CENTER);
mainFrame.setDefaultCloseOperation(3);
//setMenuBar();
mainFrame.pack();
mainFrame.setVisible(true);
}
private void setMenuBar() {
int id = 0;
for (int y = 0; y < JMENU_BUTTONS.length; y++) {
JMenu menu = new JMenu();
for (int i = 0; i < JMENU_BUTTONS[y].length; i++) {
if (i == 0) {
menu.setText((String) JMENU_BUTTONS[y][i]);
} else if (JMENU_BUTTONS[y][i] instanceof JMenuItem){
JMenuItem item = (JMenuItem) JMENU_BUTTONS[y][i];
menu.add(item);
item.setActionCommand(""+ id++);
item.addActionListener(this);
} else {
menu.add((JSeparator) JMENU_BUTTONS[y][i]);
}
}
menuBar.add(menu);
}
mainFrame.setJMenuBar(menuBar);
}
public void startClient() {
try {
//RuntimeLoader loader = new RuntimeLoader();
//Class clientclass = loader.loadClass("client");
//Applet clientApplet = (Applet) clientclass.newInstance();
//clientclass.getMethod("provideLoaderApplet",
// new Class[] { java.applet.Applet.class }).invoke(null,
// new Object[] { this });
//clientApplet.init();
//clientApplet.start();
client.provideLoaderApplet(this);
client var_client = new client();
var_client.init();
var_client.start();
} catch (Exception exception) {
exception.printStackTrace();
}
}
public URL getDocumentBase() {
return getCodeBase();
}
public URL getCodeBase() {
URL url;
try {
url = new URL(new StringBuilder().append("http://").append(mainurl)
.toString());
} catch (Exception exception) {
exception.printStackTrace();
return null;
}
return url;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (Integer.parseInt(e.getActionCommand())) {
case 1:
if (JOptionPane.showConfirmDialog(this, "Are you sure you want to quit?") == 0)
System.exit(0);
break;
case 2:
browse("http://dementhium.wikia.com/wiki/Getting_Started");
break;
case 3:
browse("http://forums.dementhium.com/showthread.php?t=143");
break;
case 4:
browse("http://dementhium.wikia.com/wiki/Dementhium_Wiki");
break;
case 5:
browse("http://dementhium.wikia.com/wiki/Dementhium_Wiki");
break;
case 6:
browse("http://forums.dementhium.com/");
break;
case 7:
browse("http://www.youtube.com/DementhiumOfficial");
break;
case 8:
browse("http://forums.dementhium.com/payments.php");
break;
case 9:
writeImage(robot.createScreenCapture(getGameScreenRectangle()));
break;
default:
System.out.println(Integer.parseInt(e.getActionCommand()));
}
}
private Rectangle getGameScreenRectangle() {
Rectangle rect = getBounds();
rect.setLocation(this.getLocationOnScreen());
return rect;
}
private void writeImage(BufferedImage createScreenCapture) {
try {
ImageIO.write(createScreenCapture, "PNG", new File("./images/capture-" + capNum++ + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void browse(String string) {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
try {
Desktop.getDesktop().browse(new URI(string));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
}
and here is ClientSettings.java, this is called from various files, args is always defined using
public String[] data;
in RunClient
public class ClientSettings {
public int PORT;
public String IPADDRESS;
public String SERVERNAME;
public ClientSettings(String[] args) {
PORT = Integer.parseInt(args[2]);
IPADDRESS = args[1];
SERVERNAME = args[0];
}
}
Line 41 of RunClient is looking for a default constructor on ClientSettings, which doesn't exist. You've defined a constructor that takes a String[], so no default constructor is generated. It looks like the code you've posted isn't what's running, because it seems to show a correct constructor call.
I had the same problem, but when writing unit tests. The test was failing with this exception when creating the object I wanted to test. I did add a new constructor in the class I was testing and I think I was running an older code which didn't have this constructor.
Cleaning and rebuilding the workspace (with maven) solved it for me.
I am making a Scripting Editor and would like to be able to run the Bash/Shell/Python/etc. scripts in the program... So far, I have a way of running them, but there is no way for the scripts to have user input; here's the code:
package com.hightide.ui.terminal;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
/**
* Created by peter on 9/1/15.
*/
public class JTerminal extends JPanel {
private final JTextArea jta;
public JTerminal(){
super();
setLayout(new BorderLayout());
jta = new JTextArea("-- HIGH TIDE SCRIPTING EDITOR VERSION 0.0 --\n");
jta.setBackground(Color.BLACK);
jta.setForeground(Color.WHITE);
jta.setEditable(false);
JScrollPane jsp = new JScrollPane(jta);
add(jsp, BorderLayout.CENTER);
}
private void execute(String command){
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
String s;
Boolean more = true;
while (more) {
s = stdInput.readLine();
if (s != null) {
jta.append(s);
}else more = false;
}
jta.append("\nErrors:\n");
more = true;
while (more){
s = stdError.readLine();
if (s != null) {
jta.append(stdError.readLine());
}else{
more = false;
}
}
}catch(Exception e){
System.out.println("Something went wrong: \n"+e.getMessage());
}
}
#SuppressWarnings("unused")
public void run(File f, String runWith, String options){ //OPTIONS MUST BE BLANK NOT NULL IF NO OPTIONS
execute(runWith+" "+f.getAbsolutePath()+" "+options);
}
}
Any help/ideas are greatly appreciated!!!
This is a modification of my previous answer to a question about executing terminal commands from within a JTextArea, but preventing the user from modifying the previously outputted text...
This version adds the ability to send text to the running process
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class QuickTerminal {
public static void main(String[] args) {
new QuickTerminal();
}
public QuickTerminal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ConsolePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface CommandListener {
public void commandOutput(String text);
public void commandCompleted(String cmd, int result);
public void commandFailed(Exception exp);
}
public class ConsolePane extends JPanel implements CommandListener, Terminal {
private JTextArea textArea;
private int userInputStart = 0;
private Command cmd;
public ConsolePane() {
cmd = new Command(this);
setLayout(new BorderLayout());
textArea = new JTextArea(20, 30);
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new ProtectedDocumentFilter(this));
add(new JScrollPane(textArea));
InputMap im = textArea.getInputMap(WHEN_FOCUSED);
ActionMap am = textArea.getActionMap();
Action oldAction = am.get("insert-break");
am.put("insert-break", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int range = textArea.getCaretPosition() - userInputStart;
try {
String text = textArea.getText(userInputStart, range).trim();
System.out.println("[" + text + "]");
userInputStart += range;
if (!cmd.isRunning()) {
cmd.execute(text);
} else {
try {
cmd.send(text + "\n");
} catch (IOException ex) {
appendText("!! Failed to send command to process: " + ex.getMessage() + "\n");
}
}
} catch (BadLocationException ex) {
Logger.getLogger(QuickTerminal.class.getName()).log(Level.SEVERE, null, ex);
}
oldAction.actionPerformed(e);
}
});
}
#Override
public void commandOutput(String text) {
SwingUtilities.invokeLater(new AppendTask(this, text));
}
#Override
public void commandFailed(Exception exp) {
SwingUtilities.invokeLater(new AppendTask(this, "Command failed - " + exp.getMessage()));
}
#Override
public void commandCompleted(String cmd, int result) {
appendText("\n> " + cmd + " exited with " + result + "\n");
appendText("\n");
}
protected void updateUserInputPos() {
int pos = textArea.getCaretPosition();
textArea.setCaretPosition(textArea.getText().length());
userInputStart = pos;
}
#Override
public int getUserInputStart() {
return userInputStart;
}
#Override
public void appendText(String text) {
textArea.append(text);
updateUserInputPos();
}
}
public interface UserInput {
public int getUserInputStart();
}
public interface Terminal extends UserInput {
public void appendText(String text);
}
public class AppendTask implements Runnable {
private Terminal terminal;
private String text;
public AppendTask(Terminal textArea, String text) {
this.terminal = textArea;
this.text = text;
}
#Override
public void run() {
terminal.appendText(text);
}
}
public class Command {
private CommandListener listener;
private ProcessRunner runner;
public Command(CommandListener listener) {
this.listener = listener;
}
public boolean isRunning() {
return runner != null && runner.isAlive();
}
public void execute(String cmd) {
if (!cmd.trim().isEmpty()) {
List<String> values = new ArrayList<>(25);
if (cmd.contains("\"")) {
while (cmd.contains("\"")) {
String start = cmd.substring(0, cmd.indexOf("\""));
cmd = cmd.substring(start.length());
String quote = cmd.substring(cmd.indexOf("\"") + 1);
cmd = cmd.substring(cmd.indexOf("\"") + 1);
quote = quote.substring(0, cmd.indexOf("\""));
cmd = cmd.substring(cmd.indexOf("\"") + 1);
if (!start.trim().isEmpty()) {
String parts[] = start.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
values.add(quote.trim());
}
if (!cmd.trim().isEmpty()) {
String parts[] = cmd.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
for (String value : values) {
System.out.println("[" + value + "]");
}
} else {
if (!cmd.trim().isEmpty()) {
String parts[] = cmd.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
}
runner = new ProcessRunner(listener, values);
}
}
public void send(String cmd) throws IOException {
runner.write(cmd);
}
}
public class ProcessRunner extends Thread {
private List<String> cmds;
private CommandListener listener;
private Process process;
public ProcessRunner(CommandListener listener, List<String> cmds) {
this.cmds = cmds;
this.listener = listener;
start();
}
#Override
public void run() {
try {
System.out.println("cmds = " + cmds);
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream();
process = pb.start();
StreamReader reader = new StreamReader(listener, process.getInputStream());
// Need a stream writer...
int result = process.waitFor();
// Terminate the stream writer
reader.join();
StringJoiner sj = new StringJoiner(" ");
cmds.stream().forEach((cmd) -> {
sj.add(cmd);
});
listener.commandCompleted(sj.toString(), result);
} catch (Exception exp) {
exp.printStackTrace();
listener.commandFailed(exp);
}
}
public void write(String text) throws IOException {
if (process != null && process.isAlive()) {
process.getOutputStream().write(text.getBytes());
process.getOutputStream().flush();
}
}
}
public class StreamReader extends Thread {
private InputStream is;
private CommandListener listener;
public StreamReader(CommandListener listener, InputStream is) {
this.is = is;
this.listener = listener;
start();
}
#Override
public void run() {
try {
int value = -1;
while ((value = is.read()) != -1) {
listener.commandOutput(Character.toString((char) value));
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
public class ProtectedDocumentFilter extends DocumentFilter {
private UserInput userInput;
public ProtectedDocumentFilter(UserInput userInput) {
this.userInput = userInput;
}
public UserInput getUserInput() {
return userInput;
}
#Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.insertString(fb, offset, string, attr);
}
}
#Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.remove(fb, offset, length); //To change body of generated methods, choose Tools | Templates.
}
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates.
}
}
}
}
So, I wrote myself a very simple Windows batch file...
#echo off
#echo Hello World!
set /p pathName=Enter The Value:%=%
#echo %pathName%
It doesn't do much, it outputs "Hello World!" and prompts the user to enter a value, which is further echoed to the screen and then terminates...
And used it to test the above code...
I am making a Scripting Editor and would like to be able to run the Bash/Shell/Python/etc. scripts in the program... So far, I have a way of running them, but there is no way for the scripts to have user input; here's the code:
package com.hightide.ui.terminal;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
/**
* Created by peter on 9/1/15.
*/
public class JTerminal extends JPanel {
private final JTextArea jta;
public JTerminal(){
super();
setLayout(new BorderLayout());
jta = new JTextArea("-- HIGH TIDE SCRIPTING EDITOR VERSION 0.0 --\n");
jta.setBackground(Color.BLACK);
jta.setForeground(Color.WHITE);
jta.setEditable(false);
JScrollPane jsp = new JScrollPane(jta);
add(jsp, BorderLayout.CENTER);
}
private void execute(String command){
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
String s;
Boolean more = true;
while (more) {
s = stdInput.readLine();
if (s != null) {
jta.append(s);
}else more = false;
}
jta.append("\nErrors:\n");
more = true;
while (more){
s = stdError.readLine();
if (s != null) {
jta.append(stdError.readLine());
}else{
more = false;
}
}
}catch(Exception e){
System.out.println("Something went wrong: \n"+e.getMessage());
}
}
#SuppressWarnings("unused")
public void run(File f, String runWith, String options){ //OPTIONS MUST BE BLANK NOT NULL IF NO OPTIONS
execute(runWith+" "+f.getAbsolutePath()+" "+options);
}
}
Any help/ideas are greatly appreciated!!!
This is a modification of my previous answer to a question about executing terminal commands from within a JTextArea, but preventing the user from modifying the previously outputted text...
This version adds the ability to send text to the running process
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class QuickTerminal {
public static void main(String[] args) {
new QuickTerminal();
}
public QuickTerminal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ConsolePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface CommandListener {
public void commandOutput(String text);
public void commandCompleted(String cmd, int result);
public void commandFailed(Exception exp);
}
public class ConsolePane extends JPanel implements CommandListener, Terminal {
private JTextArea textArea;
private int userInputStart = 0;
private Command cmd;
public ConsolePane() {
cmd = new Command(this);
setLayout(new BorderLayout());
textArea = new JTextArea(20, 30);
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new ProtectedDocumentFilter(this));
add(new JScrollPane(textArea));
InputMap im = textArea.getInputMap(WHEN_FOCUSED);
ActionMap am = textArea.getActionMap();
Action oldAction = am.get("insert-break");
am.put("insert-break", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int range = textArea.getCaretPosition() - userInputStart;
try {
String text = textArea.getText(userInputStart, range).trim();
System.out.println("[" + text + "]");
userInputStart += range;
if (!cmd.isRunning()) {
cmd.execute(text);
} else {
try {
cmd.send(text + "\n");
} catch (IOException ex) {
appendText("!! Failed to send command to process: " + ex.getMessage() + "\n");
}
}
} catch (BadLocationException ex) {
Logger.getLogger(QuickTerminal.class.getName()).log(Level.SEVERE, null, ex);
}
oldAction.actionPerformed(e);
}
});
}
#Override
public void commandOutput(String text) {
SwingUtilities.invokeLater(new AppendTask(this, text));
}
#Override
public void commandFailed(Exception exp) {
SwingUtilities.invokeLater(new AppendTask(this, "Command failed - " + exp.getMessage()));
}
#Override
public void commandCompleted(String cmd, int result) {
appendText("\n> " + cmd + " exited with " + result + "\n");
appendText("\n");
}
protected void updateUserInputPos() {
int pos = textArea.getCaretPosition();
textArea.setCaretPosition(textArea.getText().length());
userInputStart = pos;
}
#Override
public int getUserInputStart() {
return userInputStart;
}
#Override
public void appendText(String text) {
textArea.append(text);
updateUserInputPos();
}
}
public interface UserInput {
public int getUserInputStart();
}
public interface Terminal extends UserInput {
public void appendText(String text);
}
public class AppendTask implements Runnable {
private Terminal terminal;
private String text;
public AppendTask(Terminal textArea, String text) {
this.terminal = textArea;
this.text = text;
}
#Override
public void run() {
terminal.appendText(text);
}
}
public class Command {
private CommandListener listener;
private ProcessRunner runner;
public Command(CommandListener listener) {
this.listener = listener;
}
public boolean isRunning() {
return runner != null && runner.isAlive();
}
public void execute(String cmd) {
if (!cmd.trim().isEmpty()) {
List<String> values = new ArrayList<>(25);
if (cmd.contains("\"")) {
while (cmd.contains("\"")) {
String start = cmd.substring(0, cmd.indexOf("\""));
cmd = cmd.substring(start.length());
String quote = cmd.substring(cmd.indexOf("\"") + 1);
cmd = cmd.substring(cmd.indexOf("\"") + 1);
quote = quote.substring(0, cmd.indexOf("\""));
cmd = cmd.substring(cmd.indexOf("\"") + 1);
if (!start.trim().isEmpty()) {
String parts[] = start.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
values.add(quote.trim());
}
if (!cmd.trim().isEmpty()) {
String parts[] = cmd.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
for (String value : values) {
System.out.println("[" + value + "]");
}
} else {
if (!cmd.trim().isEmpty()) {
String parts[] = cmd.trim().split(" ");
values.addAll(Arrays.asList(parts));
}
}
runner = new ProcessRunner(listener, values);
}
}
public void send(String cmd) throws IOException {
runner.write(cmd);
}
}
public class ProcessRunner extends Thread {
private List<String> cmds;
private CommandListener listener;
private Process process;
public ProcessRunner(CommandListener listener, List<String> cmds) {
this.cmds = cmds;
this.listener = listener;
start();
}
#Override
public void run() {
try {
System.out.println("cmds = " + cmds);
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream();
process = pb.start();
StreamReader reader = new StreamReader(listener, process.getInputStream());
// Need a stream writer...
int result = process.waitFor();
// Terminate the stream writer
reader.join();
StringJoiner sj = new StringJoiner(" ");
cmds.stream().forEach((cmd) -> {
sj.add(cmd);
});
listener.commandCompleted(sj.toString(), result);
} catch (Exception exp) {
exp.printStackTrace();
listener.commandFailed(exp);
}
}
public void write(String text) throws IOException {
if (process != null && process.isAlive()) {
process.getOutputStream().write(text.getBytes());
process.getOutputStream().flush();
}
}
}
public class StreamReader extends Thread {
private InputStream is;
private CommandListener listener;
public StreamReader(CommandListener listener, InputStream is) {
this.is = is;
this.listener = listener;
start();
}
#Override
public void run() {
try {
int value = -1;
while ((value = is.read()) != -1) {
listener.commandOutput(Character.toString((char) value));
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
public class ProtectedDocumentFilter extends DocumentFilter {
private UserInput userInput;
public ProtectedDocumentFilter(UserInput userInput) {
this.userInput = userInput;
}
public UserInput getUserInput() {
return userInput;
}
#Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.insertString(fb, offset, string, attr);
}
}
#Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.remove(fb, offset, length); //To change body of generated methods, choose Tools | Templates.
}
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (offset >= getUserInput().getUserInputStart()) {
super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates.
}
}
}
}
So, I wrote myself a very simple Windows batch file...
#echo off
#echo Hello World!
set /p pathName=Enter The Value:%=%
#echo %pathName%
It doesn't do much, it outputs "Hello World!" and prompts the user to enter a value, which is further echoed to the screen and then terminates...
And used it to test the above code...
I create chat app one to one by using Java programming language
I faced issue: client can't send a new message until he receives a message from the server.
You should have a multithreaded application.
The client will run 2 threads:
1) Sender thread which will run on send button. You can every time create a new instance of this thread on clicking send button.
2) The receiver thread will keep on running continuously and check the stream for any message. Once it gets a message on stream it will write the same on console.
Will update you shortly with the code.
Thanks
Written this code long back similarly you can write server using other port
package com.clients;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientFullDuplex extends JFrame implements ActionListener {
private JFrame jframe;
private JPanel jp1, jp2;
private JScrollPane jsp;
private JTextArea jta;
private JTextField jtf;
private JButton send;
private Thread senderthread;
private Thread recieverthread;
private Socket ds;
private boolean sendflag;
public static void main(String[] args) {
try {
ClientFullDuplex sfd = new ClientFullDuplex();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ClientFullDuplex() throws UnknownHostException, IOException {
initGUI();
ds = new Socket("127.0.0.1", 1124);
initNetworking();
}
public void initGUI() {
jframe = new JFrame();
jframe.setTitle("Client");
jframe.setSize(400, 400);
jp1 = new JPanel();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jtf = new JTextField();
send = new JButton("Send");
send.addActionListener(this);
jp1.setLayout(new GridLayout(1, 2, 10, 10));
jp1.add(jtf);
jp1.add(send);
jframe.add(jp1, BorderLayout.SOUTH);
jframe.add(jsp, BorderLayout.CENTER);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta.append("hello client");
}
#Override
public synchronized void addWindowListener(WindowListener arg0) {
// TODO Auto-generated method stub
super.addWindowListener(arg0);
new WindowAdapter() {
#Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
if (ds != null)
try {
ds.close();
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public void initNetworking() {
try {
recieverthread = new Thread(r1);
recieverthread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Runnable r1 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Reciver Thread Started");
recieveMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Sender Thread Started");
sendMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void recieveMessage(Socket rms) throws IOException {
while (true) {
System.out.println(Thread.currentThread().getName()
+ "Reciver Functionality");
BufferedReader br = new BufferedReader(new InputStreamReader(
rms.getInputStream()));
String line = br.readLine();
System.out.println(line);
jta.append("\nServer:"+line);
}
}
public void sendMessage(Socket sms) throws IOException {
System.out.println(Thread.currentThread().getName()
+ "Sender Functionality");
PrintWriter pw = new PrintWriter(sms.getOutputStream(), true);
String sline = jtf.getText();
System.out.println(sline);
pw.println(sline);
jtf.setText("");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == send) {
senderthread = new Thread(r2);
senderthread.start();
}
}
}
This is the code I copied and edited from your earlier post.
The problem is that the input stream from socket is blocking. So my suggestion is to read up on async sockets in java and refactor the code below.
next to that it isn't that difficult to edit posts.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public static void main(String[] args) {
Server chatServer = new Server(5555);
System.out.println("###Start listening...###");
chatServer.startListening();
chatServer.acceptClientRequest();
}
private ServerSocket listeningSocket;
private Socket serviceSocket;
private int TCPListeningPort;
private ArrayList<SocketHanding> connectedSocket;
public Server(int TCPListeningPort)
{
this.TCPListeningPort = TCPListeningPort;
connectedSocket = new ArrayList<SocketHanding>();
}
public void startListening()
{
try
{
listeningSocket = new ServerSocket(TCPListeningPort);
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void acceptClientRequest()
{
try
{
while (true)
{
serviceSocket = listeningSocket.accept();
SocketHanding _socketHandling = new SocketHanding(serviceSocket);
connectedSocket.add(_socketHandling);
Thread t = new Thread(_socketHandling);
t.start();
System.out.println("###Client connected...### " + serviceSocket.getInetAddress().toString() );
}
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class SocketHanding implements Runnable
{
private Socket _connectedSocket;
private PrintWriter socketOut;
private InputStream socketIn;
private boolean threadRunning = true;
private String rmsg;
public SocketHanding(Socket connectedSocket) throws IOException
{
_connectedSocket = connectedSocket;
socketOut = new PrintWriter(_connectedSocket.getOutputStream(), true);
socketIn = _connectedSocket.getInputStream();
}
private void closeConnection() throws IOException
{
threadRunning = false;
socketIn.close();
socketOut.close();
_connectedSocket.close();
}
public void sendMessage(String message)
{
socketOut.println(message);
}
private String receiveMessage() throws IOException
{
String t = "";
if (_connectedSocket.getInputStream().available() > 0)
{
byte[] b = new byte[8192];
StringBuilder builder = new StringBuilder();
int bytesRead = 0;
if ( (bytesRead = _connectedSocket.getInputStream().read(b)) > -1 )
{
builder.append(new String(b, 0, b.length).trim());
}
t = builder.toString();
}
return t;
}
#Override
public void run()
{
while (threadRunning)
{
try
{
rmsg = receiveMessage();
System.out.println(rmsg);
if(rmsg.equalsIgnoreCase("bye"))
{
System.out.println("###...Done###");
closeConnection();
break;
}
else
{
String smsg = "";
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
smsg = keyboard.readLine();
keyboard.close();
sendMessage("Server: "+smsg);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
I'm having trouble linking the main page to the second page by the click of a button. It throws a NullPointException. Can someone please tell me where I've erred?
import java.io.InputStream;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class standings extends MIDlet implements ActionListener{
public Command cmdSelect;
public Form fform, selectLgform;
public Button btnSelectLeague,btnHelp,btnAbout,btnExit;
public TextArea taHome,taAbout, taHelp, taSelectLg;
private InputStream iStream;
private StringBuffer strBuffer;
private Form selectLgForm;
public void startApp() {
Display.init(this);
try {
Resources rs= Resources.open("/restheme.res");
UIManager.getInstance().setThemeProps(rs.getTheme("Theme2"));
} catch (Exception e) {
e.getMessage();
}
displayMainForm();
}
public void displayMainForm()
{
fform = new Form("Football League Standings");
taHome= new TextArea(5,20,TextArea.ANY);
fform.setLayout(new BorderLayout());
fform.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/intro.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taHome.setText(strBuffer.toString());
strBuffer = null;
taHome.setFocusable(false);
taHome.setEditable(false);
taHome.setUIID("Label");
//fform.addComponent(BorderLayout.CENTER,taHome);
btnSelectLeague= (new Button("Select league"));
btnHelp= (new Button("Help"));
btnAbout= (new Button("About"));
btnExit= (new Button("Exit"));
Container mcont = new Container(new BoxLayout(BoxLayout.Y_AXIS));
mcont.addComponent(taHome);
mcont.addComponent(btnSelectLeague);
mcont.addComponent(btnHelp);
mcont.addComponent(btnAbout);
mcont.addComponent(btnExit);
fform.addComponent(BorderLayout.CENTER, mcont);
btnSelectLeague.addActionListener(this);
btnHelp.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
fform.show();
}
/* Command exitCommand = new Command("Exit");
fform.addCommand(exitCommand);
fform.addCommandListener(this);
}
}*/
public void selectLgForm()
{
selectLgForm= new Form("Select League");
taSelectLg= new TextArea(5,20,TextArea.ANY);
selectLgForm.setLayout(new BorderLayout());
selectLgForm.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/selectlg.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taSelectLg.setText(strBuffer.toString());
strBuffer = null;
taSelectLg.setFocusable(false);
taSelectLg.setEditable(false);
taSelectLg.setUIID("Label");
selectLgForm.addComponent(BorderLayout.CENTER,taAbout);
//START OF MENU BUTTONS
selectLgForm.addCommand(new Command("Back")
{
public void actionPerformed(ActionEvent e)
{
displayMainForm();
}
});
selectLgForm.show();
}//END OF MENU BUTTONS
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnSelectLeague){
selectLgForm();
}
my best guesses are:
- selectLgForm.addComponent(BorderLayout.CENTER,taAbout) throws a NullPointerException because taAbout is null.
- or iStream = getClass().getResourceAsStream("/selectlg.txt"); throws a NullPointerException because the text file is not where you think it is.