Search code examples
javaswingcanvaslayout-managernull-layout-manager

How to put buttons and canvas into jframe? (Java swing)


I have a JFrame and a few buttons and text fields inside. I'm using absolute positioning (null layout). I tried creating a canvas to draw on, but when I try to add the canvas to a container and then into the frame, the canvas overwrites all buttons. I want to have the canvas next to the buttons, both visible.

This is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Gui extends JFrame {
    private JLabel labEnterWord;
    private JTextField tfWord;
    private JButton butOk;

    public Gui(String title) {
        super(title);
        JPanel p = new JPanel();
        p.setLayout(null);

        //Create components and add them to the container
        addComponents(p);

        //Add containers to window
        getContentPane().add(p);
        getContentPane().add(new MyCanvas());

        setWindowProperties();
    }

    private void addComponents(JPanel p) {
        labEnterWord = new JLabel("Enter your word:");
        labEnterWord.setBounds(100, 60, 200, 30);                   
        labEnterWord.setFont(new Font("Arial", Font.PLAIN, 20));
        p.add(labEnterWord);

        tfWord = new JTextField();
        tfWord.setBounds(100, 100, 100, 25);
        tfWord.setFont(new Font("Arial", Font.PLAIN, 14));
        p.add(tfWord);

        butOk = new JButton("OK");
        butOk.setBounds(220, 100, 51, 25);
        butOk.addActionListener(new Event());
        p.add(butOk);
    }

    private void setWindowProperties(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setSize(1280, 720);
        setResizable(false);
        setLocationRelativeTo(null);
    }
}

MyCanvas class:

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

public class MyCanvas extends JPanel {

    public void drawing(){
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawRect(500, 200, 200, 200);
    }
}

Main class just calls Gui().


Solution

  • Here:

    getContentPane().add(p);
    getContentPane().add(new MyCanvas());
    

    The first one adds your panel with your buttons to the frame. Then you add another thing to the frame!

    Following your approach of placing everything manually, you rather add that canvas to your panel!

    You disabled all means that would allow the JFrame resp. a layout manager to meaningfully place your panel and the canvas. Instead you push two elements into the frame, without telling the frame where that canvas should go to!

    So you either need absolute placement for the canvas as well - or you step back and turn to a layout manager to do that for you.