You can't do that... If you want to append text to a scrollable text
component you should use a JTextArea contained in a JScrollpane.
Since I think that seing is beleiving I have added a snippet here to show you.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextScroller extends JFrame implements ActionListener {
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
JButton closeBtn = new JButton();
JButton appendTextBtn = new JButton();
JTextField inputTextField = new JTextField();
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea scroller = new JTextArea();
JButton clearBtn = new JButton();
public TextScroller() {
try {
jbInit();
this.closeBtn.addActionListener(this);
this.appendTextBtn.addActionListener(this);
this.clearBtn.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TextScroller ts = new TextScroller();
ts.setBounds(20,20,650,300);
ts.setVisible(true);
}
/**
* Set up GUI
* @throws Exception
*/
private void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout1);
closeBtn.setText("Close");
appendTextBtn.setText("Append Text");
clearBtn.setText("Clear");
inputTextField.setText("");
inputTextField.setColumns(25);
jPanel1.add(closeBtn, null);
jPanel1.add(appendTextBtn, null);
jPanel1.add(inputTextField, null);
jPanel1.add(clearBtn, null);
scroller.setLineWrap(true);
jScrollPane1.getViewport().add(scroller, null);
this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
}
/**
* Handle button clicks
* @param e
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource()==closeBtn) System.exit(0);
else if (e.getSource()==appendTextBtn) {
String s=inputTextField.getText().trim();
if (s.length() > 0) {
scroller.append(s);
// append newline, you may leave that out. the textArea will
// wrap the lines anyway (linWrap is set to true)
scroller.append("\r\n");
}
} else if (e.getSource()==clearBtn) {
scroller.setText("");
}
}
}
Bookmarks