1

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

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

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

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

4

1 回答 1

2

在我这边,您提出的问题运行良好。如果您认为,请告诉我,这不是您的意思:-)

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

于 2013-07-01T05:36:42.823 回答