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().