[英]Extending JScrollPane to have a textarea inside
我试图将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);
}
}
像这样的东西?
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
设置为换行。 从代码中删除以下行:
textArea.setPreferredSize(new Dimension(400, 400));
这一行正在阻止textArea
增长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.