Swing – Adding JTextArea to JFrame

awtjframejpaneljtextareaswing

If I have 1 main class and 2 subclasses

  • subclass 1: public class JPanel1 extends JPanel {….properly initialized}
  • subclass 2: public class JTextArea1 extends JTextArea {… properly initialized}

Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?

My goal is to output data into both the jpanel and the jtextarea

Best Answer

Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)

import java.awt.*;
import javax.swing.*;

public class SwingExample
{
    private CustomPanel customPanel;
    private CustomTextArea customTextArea;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Swing Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(5, 5));
        contentPane.setBorder(
                BorderFactory.createLineBorder(
                                Color.DARK_GRAY, 5));
        customPanel = new CustomPanel();
        customTextArea = new CustomTextArea();

        contentPane.add(customPanel, BorderLayout.CENTER);
        contentPane.add(customTextArea, BorderLayout.LINE_START);
        frame.setContentPane(contentPane);      
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new SwingExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class CustomPanel extends JPanel
{
    private static final int GAP = 5;

    public CustomPanel()
    {
        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createLineBorder(
                Color.BLUE, GAP, true));
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(300, 300));
    }
}

class CustomTextArea extends JTextArea
{
    private static final int GAP = 5;
    public CustomTextArea()
    {       
        setBorder(BorderFactory.createLineBorder(
                Color.RED, GAP, true));
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(100, 30));
    }
}

OUTPUT :

SwingExampleImage

Related Topic