将JTextArea添加到JFrame

时间:2013-07-01 03:31:49

标签: swing jframe jpanel awt jtextarea

如果我有1个主类和2个子类

  • 子类1:公共类JPanel1扩展了JPanel {....正确初始化}
  • 子类2:公共类JTextArea1扩展JTextArea {...正确初始化}

为什么我可以执行jframe1.add(new JPanel1())而不执行jframe1.add(new JTextArea1())?对于正确初始化的JFrame jframe1 = new JFrame();?

我的目标是将数据输出到jpanel和jtextarea

1 个答案:

答案 0 :(得分:1)

在我这边,你提出的问题,工作正常。请让我知道,如果您认为,这不是您的意思: - )

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));
    }
}

输出:

SwingExampleImage