0

This might qualify as a repeat question, but no solutions I could find work for me. I have a JFrame which is my root pane, on that frame I put a JLabel, a JTextArea, and a JPanel. I have tried implementing the paint method to draw on the JPanel but it doesn't seem to work.

Here is the code:

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

Please tell me why this doesn't work.

4

1 回答 1

3

您已覆盖paintComponentCelsiusConverterGUI从未实际将组件的实例添加到其JFrame或其任何子容器中。

于 2013-09-02T18:17:36.140 回答