views:

29

answers:

1

Why my JFrame 'frame' is diplaying empty window, when it should give me 3 menu buttons and my own painted JComponent below ? What am I missing here ?

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

public class Eyes extends JFrame {

    public static void main(String[] args) {
        final JFrame frame = new JFrame("Eyes");
        frame.setPreferredSize(new Dimension(450, 300));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel players = new JPanel(new GridLayout(1, 3));
                players.add(new JButton("Eyes color"));
                players.add(new JButton("Eye pupil"));
                players.add(new JButton("Background color"));

        JPanel eyes = new JPanel();
        eyes.add(new MyComponent());

        JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        content.add(players);
        content.add(eyes);

        frame.getContentPane();
        frame.pack();
        frame.setVisible(true);
    }
}

class MyComponent extends JComponent {

    public MyComponent(){

    }

    @Override
    public void paint(Graphics g) {
        int height = 120;
        int width = 120;  
        Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        BasicStroke bs = new BasicStroke(3.0f);
        g2d.setStroke(bs);
        g2d.setColor(Color.yellow);
        g2d.fillOval(200, 200, height, width);
        g2d.setColor(Color.black);
        g2d.drawOval(60, 60, height, width);   
    }
}
+2  A: 

Your line:

    frame.getContentPane();

doesnt do anything but access the content pane of the frame. Instead of getting the content pane, you should set your content pane, like this:

    frame.setContentPane(content);

EDIT:

alternatively, as @trashgod points out, you could use the getContentPane method to access the default content pane and add your content component to that:

    frame.getContentPane().add(content);
akf
+1 Also, `frame.add(content)` via forwarding.
trashgod