我正在尝试将JTextArea
插入到JScrollPanel
中,我希望它的行为与在Microsoft Word中有两个空边的行为一样,在中间你有代码中的textArea滚动面板下方似乎没有增长,因为您插入更多文本,两个空边不存在。我做错了什么?
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
import java.awt.Dimension;
public class WorkArea extends JScrollPane{
public WorkArea(){
/* Scroll Panel settings*/
setBackground(new Color(60,60,60));
setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
getViewport().setOpaque(false);
setBorder(null);
/* Text Area */
JTextArea textArea = new JTextArea("Hello World!");
textArea.setLineWrap(true);
textArea.setPreferredSize(new Dimension(400, 400));
/* Adding the textarea to the scrollPanel */
setViewportView(textArea);
}
}
答案 0 :(得分:2)
这样的东西?
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class TextAreaInScrollPane {
JPanel gui = new JPanel(new BorderLayout());
TextAreaInScrollPane() {
// adjust columns/rows for different size
JTextArea ta = new JTextArea(10,20);
ta.setLineWrap(true);
ta.setWrapStyleWord(true); // nicer
JScrollPane jsp = new JScrollPane(
ta,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
gui.add(jsp);
// this is purely to show the bounds of the gui panel
gui.setBackground(Color.RED);
// adjust to need
gui.setBorder(new EmptyBorder(5, 15, 15, 5));
}
public JComponent getGUI() {
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
TextAreaInScrollPane taisp = new TextAreaInScrollPane();
JOptionPane.showMessageDialog(null, taisp.getGUI());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
JScrollPane
。只需使用一个实例。ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
更好,因为我们将JTextArea
设置为换行。答案 1 :(得分:0)
从代码中删除以下行:
textArea.setPreferredSize(new Dimension(400, 400));
这一行阻止textArea
成长。