Search code examples
javaswingjscrollpanejtextareajdialog

Adding JScrollPane with JTextArea into JDailog


public class DailogDemo 
{

private JDialog chatdailog;
private JTextArea chatHistory;
private JScrollPane mScrollMessage; 

DailogDemo()
{
chatdailog=new JDialog();
chatdailog.setSize(300, 400);

chatHistory=new JTextArea();
chatHistory.setPreferredSize(new Dimension(150,100));
mScrollMessage=new JScrollPane();
mScrollMessage.add(chatHistory);
mScrollMessage.setBounds(4, 10, 150, 100);
mScrollMessage.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
chatdailog.add(mScrollMessage);
chatdailog.show();
}

public static void main(String args[])
{
    new DailogDemo();
}
}

In the above code, I can't able to see the JTextArea in JScrollPane. Does anybody know what I am doing wrong?


Solution

    • use JTextArea(int rows, int columns)

    • don't set and remove chatdailog.setSize(300, 400);

    • don't set and remove chatHistory.setPreferredSize(new Dimension(150,100));

    • don't set and remove mScrollMessage.add(chatHistory); use JScrollPane scrollPane = new JScrollPane(textArea); instead

    • don't set and remove mScrollMessage.setBounds(4, 10, 150, 100);

    • don't set and remove chatdailog.show(); use chatdailog.setVisible(true);

    • add code line chatdailog.pack() before line chatdailog.setVisible(true);

    • if is there another parent for this JDialog wrap chatdailog.setVisible(true); into invokeLater()