43. 자바 TextArea 정리 + 스크롤 넣기
TextArea는 여러 줄의 text를 입력하거나 보여줄 수 있는 편집가능한 컴포넌트이다. 그리고 스크롤바를 이용해서 실제화면에 보이는 것보다 많은 양의 text를 담을 수 있다.
메서드 또는 생성자 | 설명 |
TextArea(String text, int row, int col, int scrollbar) |
text – TextArea에 보여질 text를 지정한다. row – TextArea의 줄(row) 수를 지정한다. col – TextArea의 열(column) 수를 적는다. scrollbar – TextArea에 사용할 scrollbar의 종류와 사용여부지정. 아래의 4가지 값 중에서 하나를 선택 TextArea.SCROLLBARS_BOTH TextArea.SCROLLBARS_NONE TextArea.SCROLLBARS_HORIZONTAL_ONLY TextArea.SCROLLBARS_VERTICAL_ONLY |
TextArea(int row, int col) |
row – TextArea의 줄(row) 수를 지정한다. col – TextArea의 열(column) 수를 적는다. 아무런 text도 없는 빈 TextArea를 생성한다. Scrollbar는 수평(HORIZONTAL), 수직(VERTICAL) 모두 갖는다. |
int getRows() | TextArea의 행(row)의 개수를 얻는다. |
int getColumns() | TextArea의 열(column)의 개수를 얻는다. |
void setRows(int rows) | 지정된 값으로 TextArea의 행(row)의 개수를 설정한다. |
void setColumns(int columns) | 지정된 값으로 TextArea의 열(column)의 개수를 설정한다. |
void append(String str) | TextArea에 있는 text의 맨 마지막에 문자열을 덧붙인다. |
void insert(String str, int pos) | TextArea에 있는 text의 지정된 위치에 문자열을 넣는다. |
void replaceRange(String str, int start, int end) | TextArea에 있는 text의 start부터 end범위에 있는 문자열을 str에 지정된 값으로 변경한다. |
void setText(String t) * | 지정된 문자열을 TextArea의 text로 한다. |
String getText() * | TextArea의 Text를 얻는다. |
void select(int selectionStart, int selectionEnd) * | selectionStart부터 selectionEnd까지의 text가 선택되게 한다. |
void selectAll() * | TextArea의 모든 text를 선택되게 한다. |
String getSelectedText() * | TextArea의 text중 선택된 부분을 얻는다. |
void setEditable(boolean b) * | TextArea의 Text를 편집가능(true)/불가능(false)하도록 한다. |
import java.awt.*; class TextAreaTest{ public static void main(String args[]){ Frame f = new Frame("Comments"); f.setSize(400, 220); f.setLayout(new FlowLayout()); TextArea comments = new TextArea("하고 싶은 말을 적으세요.", 10, 50); f.add(comments); //TextArea의 text전체가 선택되도록 한다. comments.selectAll(); f.setVisible(true); } } |
추가
자바로 GUI를 만들때 로그창을 JTextArea로 만들려면
1, JTextArea가 스크롤 가능하게하고
2. 로그가 발생하면 JTextArea 뒤에 내용을 붙이고 스크롤을 맨 아래로 내리면 된다.
1. JTextArea에 스크롤 넣기
: 자바 JTextArea에 스크롤을 넣는 방법은, JScrollPane안에 JTextArea를 넣으면 된다.
JTextArea txtLog = new JTextArea();
JScrollPane scrollPane = new JScrollPane(txtLog);
contentPane.add(scrollPane);
* 주의 : JTextArea.setPreferredSize를 설정하면 스크롤바가 생기지 않는다.
2. JTextArea에 내용 붙여넣기 + 맨 아래로 스크롤하기
: JTextArea txtLog가 JFrame를 확장하는 클래스의 멤버변수라 하면 다음과 같은 함수를 만들어주면 된다.
void addLog(String log)
{
txtLog.append(log + "\n"); // 로그 내용을 JTextArea 위에 붙여주고
txtLog.setCaretPosition(txtLog.getDocument().getLength()); // 맨아래로 스크롤한다.
}
* 로그가 발생할때마다 이 함수를 호출하여 로그 창의 뒤에 로그가 붙여지도록 하면 된다.
자동 줄 바꿈
Reader.ta.setLineWrap(true);
출처: https://unikys.tistory.com/211 [All-round programmer]