I am trying to make a JPanel hold a JTextArea. I want the JPanel to resize itself to match the preferredSize of the JTextArea, because that is the size necessary to display all of the text. Ultimately, I want to put an empty border between the JTextArea and the Jpanel, but I omitted that in my example code.
I also want the JPanel to have a line border around it. The code below works some of the time, but occasionally the bottom and right parts of the lineBorder disappear. Why is this happening? P.S. I know that my way of updating the size is not very elegant. Is there a better way?
Here is the code:
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);
}
}
The solution to my problem was to call revalidate() after each resize event. According to @MadProgrammer, this makes sense because resizing is typically done by the layout manager and called in response to invalidate/revalidate.