如何在Java上的JFrame上绘制JPanel

时间:2013-09-02 18:12:17

标签: java swing jframe jpanel paint

这可能有资格作为重复问题,但我找不到适合我的解决方案。我有JFrame这是我的根窗格,在该框架中我添加了JLabelJTextAreaJPanel。我已经尝试实现paint方法来绘制JPanel,但它似乎不起作用。

以下是代码:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class CelsiusConverterGUI extends JComponent{
    public static void addComponentsToPane(Container pane) {
        pane.setLayout(null);

        JPanel emptyLabel = new JPanel();
        JLabel Right = new JLabel("bye");
        JTextArea text = new JTextArea("hi");

        emptyLabel.setMaximumSize(new Dimension(900, 400));
        emptyLabel.setPreferredSize(new Dimension(900, 400));
        emptyLabel.setMaximumSize(new Dimension(900, 400));

        Right.setMaximumSize(new Dimension(450, 200));
        Right.setPreferredSize(new Dimension(450, 200));
        Right.setMaximumSize(new Dimension(450, 200));

        text.setMaximumSize(new Dimension(450, 200));
        text.setPreferredSize(new Dimension(450, 200));
        text.setMaximumSize(new Dimension(450, 200));

        pane.add(emptyLabel);
        pane.add(Right);
        pane.add(text);

        Insets insets = pane.getInsets();
        Dimension size = emptyLabel.getPreferredSize();
        emptyLabel.setBounds(0 + insets.left, 0 + insets.top,
                                        size.width, size.height);
        size = Right.getPreferredSize();
        Right.setBounds(450 + insets.left, 400 + insets.top,
                                        size.width, size.height);
        size = text.getPreferredSize();
        text.setBounds(0 + insets.left, 400 + insets.top,
                                        size.width, size.height);
    }

    public static void createAndShowGUI(){
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        addComponentsToPane(frame.getContentPane());

        Insets insets = frame.getInsets();
        frame.setSize(900 + insets.left + insets.right,
                            600 + insets.top + insets.bottom);
        frame.setVisible(true);
    }

    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public void paintComponent(Graphics g){
        super.paint(g);
        g.setColor(Color.RED);
        g.fillRect(0, 0, 90, 40);
    }
}

请告诉我为什么这不起作用。

1 个答案:

答案 0 :(得分:3)

您已在paintComponent中覆盖了CelsiusConverterGUI,但实际上从未将组件的实例添加到JFrame或其任何子容器中。