1

At the moment this program displays a frame with a circle in its center. I tried to add a JButton to the frame so I could implement an action listener later to display the circle when pressed, but right now I'm having trouble actually showing the button. Can anybody tell me how and why this is happening?

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

import java.awt.*;
import java.awt.geom.*;

public class SimonShape extends JFrame {

private JFrame f;
private JPanel p;
private JButton b1;
private JLabel lab;

public static void main(String[] args) {
    new SimonShape();
}

public SimonShape() {


    f = new JFrame("Simon Says");
    f.setVisible(true);
    f.setSize(500, 500);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    p = new JPanel();
    p.setBackground(Color.GRAY);

    b1 = new JButton("Click Here to Begin!");

    p.add(b1);
    f.add(p);
    f.setLocationRelativeTo(null);


    f.add(new DrawStuff(), BorderLayout.CENTER);

}

public class DrawStuff extends JComponent {

    public void paint(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;
        Graphics2D g3 = (Graphics2D) g;
        Graphics2D g4 = (Graphics2D) g;
        Graphics2D g5 = (Graphics2D) g;

        // assume d == 145 && e == 90

        g2.setPaint(Color.GREEN);
        g2.fill(new Arc2D.Double(150, 150, 200, 200, 145, 90, Arc2D.PIE));

        g3.setPaint(Color.BLUE);
        g3.fill(new Arc2D.Double(150, 150, 200, 200, 235, 90, Arc2D.PIE));

        g4.setPaint(Color.RED);
        g4.fill(new Arc2D.Double(150, 150, 200, 200, 325, 90, Arc2D.PIE));

        g5.setPaint(Color.YELLOW);
        g5.fill(new Arc2D.Double(150, 150, 200, 200, 55, 90, Arc2D.PIE));

    }

}

}
Ryan Hardin
  • 81
  • 2
  • 3
  • 12
  • Call `f.setVisible(true);` last. Also make sure you're initialising the UI from within the context of the Event Dispatching Thread, see [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) more details – MadProgrammer Oct 05 '15 at 04:59

2 Answers2

1

Problem is you have put the JFrame on the screen prior to adding JButton to it.

Either you can move this line f.setVisible(true); to the bottom(last line) of the constructor.

Or you may put this line f.revalidate(); after adding all required components to the JFrame.

  • null int the layout is to set the frame in the center of the screen rather than the corner. If I remove this, how else can I set it in the center? – Ryan Hardin Oct 05 '15 at 05:06
0

Change f.add(p); and add a location for the border layout. And also move your setVisible call to the end - after adding all the components.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28