我正在尝试让 JPanel 持有 JTextArea。我希望 JPanel 调整自身大小以匹配 JTextArea 的首选大小,因为这是显示所有文本所需的大小。最终,我想在 JTextArea 和 Jpanel 之间放置一个空边框,但我在示例代码中省略了它。
我还希望 JPanel 在它周围有一个线条边框。下面的代码有时会起作用,但有时 lineBorder 的底部和右侧部分会消失。为什么会这样?PS我知道我更新尺寸的方式不是很优雅。有没有更好的办法?
这是代码:
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
public class TextThoughtView extends JPanel {
private JTextArea myTextArea;
TextThoughtView(){
//configure the View
setBackground(new Color(0, 0, 0, 0));
setLayout(new BorderLayout());
myTextArea = new JTextArea();
add(myTextArea,BorderLayout.CENTER);
//configure the border
Border border = BorderFactory.createLineBorder(new Color(150,150,150));
setBorder(border);
//configure the textArea
Font font = new Font("Monospaced", Font.BOLD, 12);
myTextArea.setFont(font);
myTextArea.setBackground(new Color(50, 50, 50)); //same as the color of the canvas.
myTextArea.setForeground(new Color(255, 255, 255)); //sets the text color
//myTextArea.setBorder(new EmptyBorder(new Insets(5,5,5,5)));
myTextArea.getDocument().addDocumentListener(new MyDocumentListener()); //add a listener for text changes
myTextArea.setSize(new Dimension(10,20));
//sync this's size with the textArea
sizeToFitTextArea();
}
//accessors
private void sizeToFitTextArea(){
setSize(myTextArea.getPreferredSize().width,myTextArea.getPreferredSize().height);
}
private class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
sizeToFitTextArea();
}
public void removeUpdate(DocumentEvent e) {
sizeToFitTextArea();
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
}
public static void main(String args[]){
JFrame myFrame = new JFrame();
myFrame.setLayout(new BorderLayout());
myFrame.setSize(new Dimension(400,300));
JPanel myPanel = new JPanel();
myPanel.add(new TextThoughtView());
myPanel.setBackground(new Color(50,50,50));
myFrame.add(myPanel,BorderLayout.CENTER);
myFrame.setVisible(true);
}
}