Reputation: 57
I'm trying to use my program's output text area UI element to print progress and updates for my program rather than using the console output inside of Eclipse. Is a way I could say:
System.out.println(string);
but instead of printing to the console, print to my own text area on the UI. My code looks a little something like this (I've removed my other panel elements to focus more on this):
This is my MainPanel
class, where I make the element I want to print to:
public class MainPanel extends JPanel{
private JTextArea consoleOutput;
private JButton submitButton;
public MainPanel(){
setLayout(null);
Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
Font f1 = new Font("Arial", Font.PLAIN, 14);
consoleOutput = new JTextArea();
consoleOutput.setBounds(199, 122, 375 , 210);
consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0)));
consoleOutput.setEditable(false);
consoleOutput.setFont(f1);
submitButton = new JButton("Get Cards");
submitButton.setBounds(35, 285, 107, 49);
submitButton.setFont(f2);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String username = "HenryJeff";
String password = "Password";
Cards cards = new Cards();
cards.openTabs(username,password);
}
});
add(consoleOutput);
add(submitButton);
}
}
This is my Cards
class:
public class Cards{
public void openTabs(String username, String password){
System.out.println(username + ", " + password);
}
How can I replace the System.out.println();
to print to my text area? I've tried making my Cards
class extend my JPanel
and have the console text area be made and created in there, and then adding a write to method that writes to the text area but it didn't work. Any help is appreciated!
Upvotes: 1
Views: 54
Reputation: 1626
You can do that, by creating a bridge between the Document
of a JTextArea
and a Writer
:
public class PlainDocumentWriter extends PlainDocument implements Writer {
public Writer append(char c) {
// Note: is thread-safe. can share between threads.
insertString(getLength(), Char.toString(c), new SimpleAttributeSet());
}
public Writer append(CharSequence csq) {
insertString(getLength(), csq.toString(), new SimpleAttributeSet());
}
// etc.
}
Then:
PlainDocumentWriter w = new PlainDocumentWriter();
consoleOutput = new JTextArea(w);
PrintWriter pw = new PrintWriter(w);
And then:
pw.println(username + ", " + password);
Now, anything you write to the PrintWriter
will show up in the text area.
Upvotes: 1
Reputation: 4135
In your MainPanel
class
cards.openTabs(username,password,this);
and specify your consoleOutput
as non private
some default.
Change your Cards
class
public class Cards{
public void openTabs(String username, String password, MainPanel panel){
panel.consoleOutput.setText(username + ", " + password);
//now both user name and password will be displayed in text area of MainPanel class.
}
Upvotes: 1