문제 :
JTextArea
구성 요소에 대한 컨테이너로 간주하는 것은,이 코드를 시도
- 경계를 설정하여 JTextArea의 크기를 제한합니다. setBounds, setSize 또는 setPreferredSize를 사용하여이 작업을 수행 할 때마다 JTextArea의 크기를 으로 고정하고을 지정하므로이 크기보다 큰 텍스트가 추가되면 확장되지 않습니다. 일반적으로 JTextArea가 필요에 따라서 전개되지 않기 때문에, 필요에 따라서 JScrollPane에 스크롤 바가 표시되지 않게됩니다.
- 널 레이아웃을 사용 중입니다. null 레이아웃과
setBounds()
은 복잡한 GUI를 만드는 가장 쉽고 좋은 방법처럼 Swing 초보자처럼 보일 수 있지만 더 많은 스윙 GUI를 사용하면 더 어려울 수 있습니다. 그들은 GUI의 크기를 조정할 때 구성 요소의 크기를 조정하지 않으며, 향상 시키거나 유지 보수 할 왕가이며, 스크롤 패널에 배치 될 때 완전히 실패합니다. 원래 플랫폼과 다른 모든 플랫폼이나 화면 해상도에서 볼 때 끔찍한 것처럼 보입니다. .
- JTextArea를 GUI와 JScrollPane이라는 두 컨테이너에 추가하면 Swing GUI에서는 허용되지 않습니다. 대신
:
이
- 가 JTextArea에의 두 INT 생성자에 다음을 전달하여 달성하기 위해 행과 열 특성, 뭔가 쉬운을 설정하여 JTextArea에의 볼 크기을 제한합니다.
- 중첩 된 JPanels를 사용합니다. 각각 고유 한 레이아웃을 사용하여 복잡하면서도 유연하고 매력적인 GUI를 구현할 수 있습니다.
- JTextArea를 JScrollPane의 뷰포트에만 추가 한 다음 JScrollPane을 GUI에 추가하십시오. 예를 들어
는 상단에 버튼을, 당신의 GUI의 중심에서 JScrollPane의 내부에 JTextArea에를 원하고 JTextField로 및 아래 제출 버튼을, 일반적인 채팅 창 유형의 응용 프로그램, 당신은 전체를 만들 수 있다고 말한다 말한다 BorderLayout을 레이아웃하고, GridLayout을 사용하여 JPanel에 버튼을 추가하고, BoxLayout에 JPanel을 JTextField와 함께 사용하고 제출 버튼을 아래쪽으로, JTextArea를 중심으로 JScrollPane을 추가합니다.
를하고 코드는 다음과 같이 수 있습니다 : 그것은 다음과 같을 수
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
@SuppressWarnings("serial")
public class Experiment2 extends JPanel {
private static final int ROWS = 20;
private static final int COLUMNS = 50;
private static final int GAP = 3;
// create the JTextArea, setting its rows and columns properties
private JTextArea tarea = new JTextArea(ROWS, COLUMNS);
private JTextField textField = new JTextField(COLUMNS);
public Experiment2() {
// create the JScrollPane and pass in the JTextArea
JScrollPane scrollPane = new JScrollPane(tarea);
// let's create another JPanel to hold some buttons
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Load"));
buttonPanel.add(new JButton("Whatever"));
buttonPanel.add(new JButton("Exit"));
// create JPanel for the bottom with JTextField and a button
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(textField);
bottomPanel.add(Box.createHorizontalStrut(GAP));
bottomPanel.add(new JButton("Submit"));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
// use BorderLayout to add all together
setLayout(new BorderLayout(GAP, GAP));
add(scrollPane, BorderLayout.CENTER); // add scroll pane to the center
add(buttonPanel, BorderLayout.PAGE_START); // and the button panel to the top
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
Experiment2 mainPanel = new Experiment2();
JFrame frame = new JFrame("Experiment 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
편집
보다는 어떻게 작동하고 무엇을 추측 하지마, GUI를 만들고 실험 해보자. t에는 두 개의 JTextAreas가 있습니다. 하나는 columns 및 rows 속성이 colRowTextArea 변수에 의해 설정되고 유지되는 위치이고 다른 하나는 JTextArea의 기본 크기가 설정되는 위치이고 다른 하나는 변수를 prefSizeTextArea라고합니다.
우리는 방법을 만들 것이다, 우리가 JScrollPane의에 JTextArea에 배치 setUpTextArea(...)
는 JPanel에이 점을 배치하고, JTextArea에로 많은 텍스트를 추가하는 버튼이, 그리고 행동에 무슨 일이 일어 나는지 텍스트가 추가 될 때의 JTextArea
여기에 코드이고 버튼을 누르고 직접보고 어느 스크롤 :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class TwoTextAreas extends JPanel {
// our nonsense String
public static final String LoremIpsum = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit, sed do eiusmod tempor incididunt "
+ "ut labore et dolore magna aliqua. Ut enim ad minim veniam, "
+ "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
+ "commodo consequat. Duis aute irure dolor in reprehenderit in "
+ "voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
+ "Excepteur sint occaecat cupidatat non proident, sunt in culpa "
+ "qui officia deserunt mollit anim id est laborum.";
private static final int ROWS = 30;
private static final int COLS = 40;
private static final Dimension TA_PREF_SIZE = new Dimension(440, 480);
private JTextArea colRowTextArea = new JTextArea(ROWS, COLS);
private JTextArea prefSizeTextArea = new JTextArea();
public TwoTextAreas() {
setLayout(new GridLayout(1, 0));
prefSizeTextArea.setPreferredSize(TA_PREF_SIZE);
add(setUpTextArea(colRowTextArea, "Set Columns & Rows"));
add(setUpTextArea(prefSizeTextArea, "Set Preferred Size"));
}
private JPanel setUpTextArea(JTextArea textArea, String title) {
// allow word wrapping
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new AppendTextAction(textArea)));
JPanel holderPanel = new JPanel(new BorderLayout());
holderPanel.setBorder(BorderFactory.createTitledBorder(title));
holderPanel.add(scrollPane);
holderPanel.add(buttonPanel, BorderLayout.PAGE_END);
return holderPanel;
}
private class AppendTextAction extends AbstractAction {
private JTextArea textArea;
private StringBuilder sb = new StringBuilder();
public AppendTextAction(JTextArea textArea) {
super("Append Text to TextArea");
this.textArea = textArea;
// create nonsense String
for (int i = 0; i < 100; i++) {
sb.append(LoremIpsum);
sb.append("\n");
}
}
@Override
public void actionPerformed(ActionEvent e) {
textArea.append(sb.toString());
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Two TextAreas");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TwoTextAreas());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
이 질문에 http://stackoverflow.com/questions/10177183/java-add-scroll-into-를 참조하십시오 text-area –
코드에서이 줄을 제거해보십시오'add (tarea); ' – Arvind
그 방법을 시도했지만'JTextArea' 자체가 사라집니다. –