简体   繁体   中英

Shape will not appear when I add JButton to JPanel

I'm trying to make a panel that contains a shape and a button. The issue is that when I add a button to the JPanel, the shape does not appear. It just shows the button on the top of my screen. The square only shows up when add the square to the frame instead of the panel, but the button will not appear.

public static void main(String[] args)
{
    JFrame frame = new JFrame();
    JPanel panel = new JPanel(); 
    //Replace FRAME_WIDTH/HEIGHT with a number greater than 100
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setTitle("Square Game");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Creates a Red Square from RedSquare 
    final RedSquare red = new RedSquare();
    panel.add(red);

    JButton button = new JButton();
    button.setText("Red");
    panel.add(button);

    frame.add(panel);

    frame.setVisible(true);

}

public class RedSquare extends JComponent
{
private Square sq;
private int x = 100;
private int y = 0;
private Graphics2D g2;

public RedSquare()
{
    sq = new Square(x,y,Color.red);
}

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;
    sq.draw(g2);
}

public int getX()
{
    return x;
}

public int getY()
{
    return y;
}

public void moveBy()
{
    y++;
    sq = new Square(x,y,Color.red);
    repaint();
}
}

public class Square
{
private int x;
private int y;
private Color color;

public Square(int x, int y, Color color)
{
    this.x = x;
    this.y = y;
    this.color = color;
}

public void draw(Graphics2D g2)
{
    Rectangle body = new Rectangle(x, y, 40, 40);
    g2.draw(body);
    g2.setPaint(color);
    g2.fill(body);
    g2.draw(body);
}
}

Do I need to do something else to make this work? Am I missing something? I am new to this and any help is greatly appreciated.

I think you have to set layout in panel using panel.setLayout(new FlowLayout()); before adding anything into panel, to make it show your both shapes. As it is overriding right now .

When adding components to a JFrame try using the setContentPane rather than add. So from your example above, remove the frame.add(panel); and use frame.setContentPane(panel);

It is unusual that you are extending JComponent which is abstract - though not prohibited.

One solution is to use JPanel instead of JComponent.

And also setting the x coordinate to x=0 will show you the square.

Beyond that you can use a layout etc:

panel.setLayout(new BorderLayout());

....


panel.add("Center", red);


.......

panel.add("South", button);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM