Trying to copy text from one JFrame to another JFrame
Hi,
Long time no post!
This one has been bugging me for a while and I can't get my head around it.
I have 2 JFrames (JCB and EngineProcess). EngineProcess runs an evaluation routine and outputs the results to a JTextField called 'textArea'. I would like to send the results instead to a JTextField called 'textPositionEvaluationOutput' on my main JFrame (JCB) but nothing happens? Here is my code?
Code:
jcb.textPositionEvaluationOutput.setText(textArea.getText());
Here is the code of the evaluation routine if it helps (I did not write this btw)
Code:
private void getEngineOutput(Process engine) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(engine.getInputStream()), 1);
String lineRead = null;
while((lineRead = reader.readLine()) != null) {
textArea.append(lineRead);
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength() - 0);
}
Any thoughts/pointers anyone?
Thanks
Re: Trying to copy text from one JFrame to another JFrame
Code out of context is hard to understand.
Where is the first posted code located? Class and method
What is the variable jcb?
Where is the variable textArea defined? Is there more than one variable with that name?
Bottom line, you need to show where all these variables are located.
What does: textArea.getText() return before it is added to textPositionEvaluationOutput?
Add a println to show its value before it is added to be sure there is something there.
Re: Trying to copy text from one JFrame to another JFrame
Hi Norm,
Thanks for your help. I actually solved the issue of copying data from one JFrame to another (in a roundabout way, but at least it works) and my data now appears where I want it to appear (under a JTabbedPane in my class called 'Chat').
However, I need your assistance with this. The data is constantly changing but the 'getText' command only picks up the data at a point in time, therefore what I would like to do is to send the data directly to a JTabbedPane in my class called 'Chat' instead of appearing in the JFrame in class EngineProcess.
I have attached a screenshot to provide context and to show the interface to show you what I am trying to achieve.
Edited code from my two main classes is attached below. Also, I attach the full 'work in progress' source code in case you need to see it all.
Appreciate your help
EngineProcess.java
Code:
package jchessboard;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EngineProcess extends JFrame implements WindowListener
{
private JScrollPane textScroll;
private JTextArea textArea;
//private ChessEditor chessEditor;
private String engineFileName;
public String engineOutputThread;
private Process engine = null;
private Thread engineThread;
private Thread engineInput;
private Thread engineOutput;
private PrintWriter writer;
private JChessBoard jcb; //Shortcut to call methods of this instance.
private Chat chat;
public EngineProcess(JChessBoard jcb, String engineFileName) {
this.jcb = jcb;
this.engineFileName = engineFileName;
///...
textArea = new JTextArea("", 15, 60);
textArea.setEditable(false);
textScroll = new JScrollPane(textArea);
//textScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.setTitle("Chess Engine");
this.addWindowListener(this);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textScroll);
this.pack();
this.setSize(1000, 150);
this.setResizable(true);
this.setLocation(new Point(100, 600));
this.setVisible(true);
}
public String getEngineOutput()
{
return textArea.getText();
}
public void runEngineThread() {
try {
engine = Runtime.getRuntime().exec(engineFileName);
Runnable r2 = new Runnable() {
public void run() {
openEngineInput(engine);
}
};
Runnable r1 = new Runnable() {
public void run() {
getEngineOutput(engine);
}
};
engineInput = new Thread(r2);
engineInput.setDaemon(true);
engineOutput = new Thread(r1);
engineOutput.setDaemon(true);
engineInput.start();
engineOutput.start();
}
catch(Exception e) {
}
}
public void runEngine() {
Runnable r1 = new Runnable() {
public void run() {
runEngineThread();
}
};
engineThread = new Thread(r1);
engineThread.setDaemon(true);
engineThread.start();
try {
while (writer == null)
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void openEngineInput(Process engine) {
try {
writer =
new PrintWriter(
new OutputStreamWriter(engine.getOutputStream()));
}
catch(Exception e) {
e.printStackTrace();
}
}
public void talkToEngine(String string) {
try {
if (writer != null) {
System.out.println(string);
writer.println(string);
writer.flush();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private void getEngineOutput(Process engine) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(engine.getInputStream()), 1);
String lineRead = null;
while((lineRead = reader.readLine()) != null) {
textArea.append(lineRead);
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength() - 0);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void stopEngine() {
if (isEngineRunning()) {
try {
writer.close();
}
catch(Exception e) {
e.printStackTrace();
}
writer = null;
engine.destroy();
engine = null;
dispose();
}
}
public boolean isEngineRunning() {
return engine != null;
}
}
Chat.java
Code:
package jchessboard;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Keymap;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.Position;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
class Chat extends JPanel {
private DefaultListModel visibleList;
private JList chatJList;
private JViewport chatViewport;
private JTextArea jTextArea1;
private JScrollPane jScrollPane1;
private JTabbedPane jTabbedPane1;
private JScrollPane scrollPane;
private JChessBoard jcb;
private JTextField textfield;
private JScrollBar scrollBar;
private JTextPane textPane;
private Component view;
private DefaultStyledDocument document;
private Position endPosition;
private int replaceOffset = -1;
private java.util.List inputHistory = new java.util.Vector();
private int inputHistoryIndex = 0;
EngineProcess engineProcess;//chess engine
//Default constructor
Chat() {
}
public static String getVersion() {
return "$Id$";
}
public void showMessage(String message) {
showMessagePart(message + "\n");
}
public void showMessageOutputEngineAnalysis(String message) {
showReplaceableMessage(message + "\n");
}
//Show analysis as a complete new line in the chat window
public void showMessageAnalysis(String message) {
showMessagePart(message);
}
public void showMessagePart(String message) {
showMessagePart(message, "regular", false);
}
public void showMessage(String message, String style) {
if (message.length() > 0)
message += "\n";
showMessagePart(message, style, false);
}
public void showReplaceableMessage(String message) {
showReplaceableMessage(message, "PGNComment");
}
public void showReplaceableMessage(String message, String style) {
if (message.length() > 0)
message += "\n";
jTextArea1.setText(message);
}
public void showMessagePart(
String message,
String style,
boolean replaceable) {
final String lmessage = message;
final String lstyle = style;
final boolean lreplaceable = replaceable;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
synchronized (document) {
if (replaceOffset != -1) {
document.remove(
replaceOffset,
endPosition.getOffset() - replaceOffset - 1);
}
if (lreplaceable)
replaceOffset = endPosition.getOffset() - 1;
else
replaceOffset = -1;
document.insertString(
endPosition.getOffset() - 1,
lmessage,
textPane.getStyle(lstyle));
}
textPane.setCaretPosition(document.getLength());
} catch (BadLocationException e) {
System.out.println(e);
}
scrollBar.setValue(Integer.MAX_VALUE);
}
});
}
public void showActionMessagePart(String message, String action) {
final MutableAttributeSet attributes = textPane.getStyle("action");
final String lmessage = message;
attributes.addAttribute("action", action);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
synchronized (document) {
try {
document.insertString(
endPosition.getOffset() - 1,
lmessage,
attributes);
} catch (BadLocationException e) {
}
}
}
});
}
public void parseInput(String message) {
//...
}
public Chat(JChessBoard jcb) {
super(new BorderLayout());
this.jcb = jcb;
setBorder(new javax.swing.border.EtchedBorder());
this.setPreferredSize(new java.awt.Dimension(329, 121));
{
jTabbedPane1 = new JTabbedPane();
this.add(jTabbedPane1, BorderLayout.CENTER);
jTabbedPane1.setPreferredSize(new java.awt.Dimension(325, 93));
{
scrollPane = new JScrollPane();
jTabbedPane1.addTab("Chat", null, scrollPane, null);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
{
jScrollPane1 = new JScrollPane();
jTabbedPane1.addTab("Engine", null, jScrollPane1, null);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
{
jTextArea1 = new JTextArea();
jScrollPane1.setViewportView(jTextArea1);
jTextArea1.setText(jcb.getName());
}
}
}
document = new DefaultStyledDocument();
endPosition = document.getEndPosition();
textPane = new JTextPane(document);
textPane.setEditable(false);
//scrollPane.setPreferredSize(new Dimension(1,jcb.settings.chatSize));
scrollBar = scrollPane.getVerticalScrollBar();
chatViewport = scrollPane.getViewport();
chatViewport.add(textPane);
// chatViewport.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
view = chatViewport.getView();
//Initialize some styles.
Style def =
StyleContext.getDefaultStyleContext().getStyle(
StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", def);
StyleConstants.setFontFamily(def, "SansSerif");
Style s = textPane.addStyle("italic", regular);
StyleConstants.setItalic(s, true);
s = textPane.addStyle("annotation", regular);
StyleConstants.setFontFamily(s, "Serif");
StyleConstants.setBold(s, true);
s = textPane.addStyle("action", regular);
StyleConstants.setUnderline(s, true);
StyleConstants.setForeground(s, new Color(0, 0, 255));
s = textPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);
s = textPane.addStyle("help", regular);
StyleConstants.setBold(s, true);
StyleConstants.setFontFamily(s, "Monospaced");
s = textPane.addStyle("chatIn", regular);
StyleConstants.setBold(s, true);
StyleConstants.setForeground(s, jcb.settings.chatColorOpponent);
s = textPane.addStyle("chatOut", regular);
StyleConstants.setBold(s, true);
StyleConstants.setForeground(s, jcb.settings.chatColorYou);
s = textPane.addStyle("small", regular);
StyleConstants.setFontSize(s, 8);
s = textPane.addStyle("debug", regular);
StyleConstants.setFontSize(s, 8);
StyleConstants.setForeground(s, jcb.settings.chatColorDebug);
s = textPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 16);
textfield = new JTextField();
textfield.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String message = textfield.getText();
textfield.setText("");
parseInput(message);
}
});
Keymap keymap = textfield.getKeymap();
keymap
.addActionForKeyStroke(
KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0),
new AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (inputHistoryIndex > 0)
inputHistoryIndex--;
if (inputHistory.size() > 0)
textfield.setText(
(String) inputHistory.get(inputHistoryIndex));
}
});
keymap
.addActionForKeyStroke(
KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0),
new AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (inputHistoryIndex < inputHistory.size())
inputHistoryIndex++;
if (inputHistoryIndex == inputHistory.size())
textfield.setText("");
else
textfield.setText(
(String) inputHistory.get(inputHistoryIndex));
}
});
keymap
.addActionForKeyStroke(
KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0),
new AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
inputHistoryIndex = inputHistory.size();
textfield.setText("");
}
});
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new BorderLayout());
messagePanel.setBorder(
javax.swing.border.LineBorder.createBlackLineBorder());
messagePanel.add("Center", textfield);
messagePanel.add("East", jcb.connectionIndicator);
add("South", messagePanel);
textPane.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
AttributeSet attributes =
document
.getCharacterElement(textPane.viewToModel(e.getPoint()))
.getAttributes();
if (attributes.isDefined("action")) {
Object action = attributes.getAttribute("action");
if (action instanceof String)
parseInput((String) action);
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
});
}
}
Re: Trying to copy text from one JFrame to another JFrame
I should add, if you wish to load an engine you can do so from this link, which is also my test engine.
http://www.webkikr.com/
Re: Trying to copy text from one JFrame to another JFrame
Quote:
I would like to do is to send the data directly to a JTabbedPane in my class called 'Chat'
Can you explain why you can't do that? Have a setXXX method in the class that controls what is displayed in the JTabbedPane that can receive the data as it is created.
In the data generator code:
refToJTabbedPaneClass.setData(theData); // call method and pass the data
Re: Trying to copy text from one JFrame to another JFrame
Quote:
Originally Posted by
Norm
Have a setXXX method in the class that controls what is displayed in the JTabbedPane that can receive the data as it is created.
In the data generator code:
refToJTabbedPaneClass.setData(theData); // call method and pass the data
I had tried this approach but it does not work. For example, I created a setXXX method in the 'Chat' class which controls what is displayed in the JTabbedPane.
Chat.java
Code:
public void setEngineDisplayOutput(String lineRead)
{
if (engineProcess != null) {
showMessageOutputEngineAnalysis("Engine Output1" + lineRead);//update engine display(lineRead);
}
}
This is the code for the data generator code in class EngineProcess.java
Code:
private void getEngineOutput(Process engine) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(engine.getInputStream()), 1);
String lineRead = null;
while((lineRead = reader.readLine()) != null) {
textArea.append(lineRead);
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength() - 0);
// call display method and pass the data
//chat.setEngineDisplayOutput(lineRead);
System.out.println(lineRead);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
Notice my commented call method. When I uncomment this line I get a nullpointer exception (at this line) but yet when I comment it out it works great in that the engine processes data as normal; interestingly the engine prints the first line of the data before the nullpointer exception occurs but only within the JFrame's window itself and not my JTabbedPane. As hard as I am try I cannot seem to send 'newly created data' directly to the JTabbedPane yet I can return 'snapshot' data using a getmethod in my class EngineProcess as follows.
Code:
public String getEngineDisplayOutput()
{
return textArea.getText();
}
BTW, Everything also prints fine to System.out.println when my call method is commented out.
Any thoughts? Want me to upload updated java files so you can take a look?
Re: Trying to copy text from one JFrame to another JFrame
Quote:
when I uncomment this line I get a nullpointer exception
Where do you set the value of the chat variable? Is that what is null?
Re: Trying to copy text from one JFrame to another JFrame
chat variable is undefinded.
I have only created a reference to it, i.e.
Code:
public class EngineProcess extends JFrame implements WindowListener
{
private JScrollPane textScroll;
private JTextArea textArea;
private String engineFileName;
public String engineOutputThread;
private Process engine = null;
private Thread engineThread;
private Thread engineInput;
private Thread engineOutput;
private PrintWriter writer;
private JChessBoard jcb; //Shortcut to call methods of this instance.
private Chat chat;//<= here is my reference
Re: Trying to copy text from one JFrame to another JFrame
Now you need to give it the value of the Chat instance. One way is to pass a reference in the EngineProcess class constructor
Re: Trying to copy text from one JFrame to another JFrame
Here is the constructor, but I am not sure what value to give the Chat instance. Can you help?
Thanks
Code:
public EngineProcess(JChessBoard jcb, String engineFileName) {
this.jcb = jcb;
this.engineFileName = engineFileName;
chat = null;
try {
Re: Trying to copy text from one JFrame to another JFrame
Pass the reference to the Chat instance in the constructor call
public EngineProcess(JChessBoard jcb, String engineFileName, Chat chat) {
this.chat = chat;
...
Re: Trying to copy text from one JFrame to another JFrame
Very good Norm, I had looked over all examples that I had worked on in the past and worked out how to pass the reference to the Chat instance. I am glad to say that I have got it working, however (there's always a but :-) ) it only displays one line at a time instead of 30-40 lines it usually produces?
I am not sure how to make display all the lines. Again, and thanks for your help so far, but how do I do this?
Thanks
Re: Trying to copy text from one JFrame to another JFrame
Quote:
it only displays one line at a time instead of 30-40 lines it usually produces?
Are you using setText or append?
Re: Trying to copy text from one JFrame to another JFrame
sorted, thanks!! Was using setText - converted to append.
One more thing. I no longer need the JFrame but I need the engine to run in my EngineProcess.java class. How do i stop the JFrame appearing?
Here is the code
Code:
package jchessboard;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EngineProcess extends JFrame implements WindowListener
{
private JScrollPane textScroll;
private JTextArea textArea;
private String engineFileName;
public String engineOutputThread;
private Process engine = null;
private Thread engineThread;
private Thread engineInput;
private Thread engineOutput;
private PrintWriter writer;
private JChessBoard jcb; //Shortcut to call methods of this instance.
private Chat chat;
public EngineProcess(JChessBoard jcb, String engineFileName, Chat chat) {
this.jcb = jcb;
this.engineFileName = engineFileName;
this.chat = chat;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (InstantiationException e) {}
catch (ClassNotFoundException e) {}
catch (UnsupportedLookAndFeelException e) {}
catch (IllegalAccessException e) {}
/*
if (!(new File(engineFileName)).exists()) {
FileIO.getInstance().alert(
chessEditor, "Chess engine " + engineFileName + " not found");
System.exit(0);
}
*/
textArea = new JTextArea("", 15, 60);
textArea.setEditable(false);
textScroll = new JScrollPane(textArea);
//textScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.setTitle("Chess Engine");
this.addWindowListener(this);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textScroll);
this.pack();
this.setSize(1000, 150);
this.setResizable(true);
this.setLocation(new Point(100, 600));
this.setVisible(true);
}
public void runEngineThread() {
try {
engine = Runtime.getRuntime().exec(engineFileName);
Runnable r2 = new Runnable() {
public void run() {
openEngineInput(engine);
}
};
Runnable r1 = new Runnable() {
public void run() {
getEngineOutput(engine);
}
};
engineInput = new Thread(r2);
engineInput.setDaemon(true);
engineOutput = new Thread(r1);
engineOutput.setDaemon(true);
engineInput.start();
engineOutput.start();
}
catch(Exception e) {
}
}
public void runEngine() {
Runnable r1 = new Runnable() {
public void run() {
runEngineThread();
}
};
engineThread = new Thread(r1);
engineThread.setDaemon(true);
engineThread.start();
try {
while (writer == null)
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void openEngineInput(Process engine) {
try {
writer =
new PrintWriter(
new OutputStreamWriter(engine.getOutputStream()));
}
catch(Exception e) {
e.printStackTrace();
}
}
public void talkToEngine(String string) {
try {
if (writer != null) {
System.out.println(string);
writer.println(string);
writer.flush();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private void getEngineOutput(Process engine) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(engine.getInputStream()), 1);
String lineRead = null;
while((lineRead = reader.readLine()) != null) {
textArea.append(lineRead);
chat.showEngineAnalysis(lineRead);
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength() - 0);
System.out.println(lineRead);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getEngineDisplayOutput()
{
return textArea.getText();
}
/** setup a new position
protected void setBoard(String fen)
{
if (canFeature("setboard")) {
printOut.print("setboard ");
printOut.println(fen);
}
else
throw new RuntimeException("setboard not supported");
} */
public void stopEngine() {
if (isEngineRunning()) {
try {
writer.close();
}
catch(Exception e) {
e.printStackTrace();
}
writer = null;
engine.destroy();
engine = null;
dispose();
}
}
public boolean isEngineRunning() {
return engine != null;
}
public void windowOpened(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
stopEngine();
}
public void windowClosed(WindowEvent e) {
}
}
Re: Trying to copy text from one JFrame to another JFrame
How do i stop the JFrame appearing?
Don't set it visible.
Why extend JFrame if you are not going to see it?
Remove the extends JFrame
Re: Trying to copy text from one JFrame to another JFrame
Cool, worked first time - again thanks!
I swear this is the last request on this thread lol. How do I invoke a 'System.exit(0)' when closing my main JFrame as the engine is still running in the background, i.e. I would like to change my 'setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);'
Re: Trying to copy text from one JFrame to another JFrame
Add a window listener. it has methods where you can put your System.exit() call.
Re: Trying to copy text from one JFrame to another JFrame
Ok Norm, thanks for all your help.
I can take it form here.
ATB