Search code examples
javaswingawtlayout-managerborder-layout

Adding JButton and rectangle to JFrame


Here's my simple code which draws rectangle on frame.How can I add button to this frame? I tried to set FlowLayout but then rectangle is not visible.Help please.

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

public class test extends Canvas{
public static JFrame frame;
public static JButton button;

public void paint(Graphics graphics) {
    graphics.setColor(Color.yellow);
    graphics.fillRect(10, 10, 100, 100);
    graphics.setColor(Color.red);
    graphics.drawRect(10, 10, 100, 100);
}

public static void main(String args[]){
    test x=new test();
    frame=new JFrame();
    button=new JButton();

    button.setSize(20,20);
    button.setText("Click");

    frame.setSize(500,500);
    frame.add(button);
    frame.add(x);
    frame.setVisible(true);     
}
}

Solution

  • The default layout for a JFrame is BorderLayout which can only accept one component per layout constraint. The default when none is specified is CENTER. So change:

    frame.add(button);
    frame.add(x);
    

    To:

    frame.add(button, BorderLayout.PAGE_START);
    frame.add(x);
    

    And you should see both components.

    Other tips:

    1. Don't set the size of top level containers. Instead layout the content & call pack().
    2. Don't mix Swing & AWT without good reason. As the other poster mentioned, we'd typically use a JPanel for custom rendering in Swing.
    3. The BorderLayout will ignore the size of the button and stretch it to fit. To have it stay a certain size, set a preferred size and add it to a FlowLayout. Add the FlowLayout to the PAGE_START constraint.