I try do display a text at the bottom of the container (JFrame) but it doesn't appear ....
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Peintre extends JFrame implements MouseMotionListener {
private int valeurX ;
private int valeurY;
public Peintre() {
super("Programme simple de dessin");
addMouseMotionListener(this);
JLabel label = new JLabel("Tirer sur la souris pour dessiner");
label.setForeground(Color.PINK);
label.setFont(new Font("Arial", Font.PLAIN, 20));
add(label,BorderLayout.SOUTH);
setSize(700, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
g.fillOval(valeurX, valeurY, 15, 15);
}
public void mouseDragged(MouseEvent e) {
valeurX = e.getX();
valeurY = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new Peintre();
}
}
I tried :
- Check width and height of the container
- set position of the label inside the frame
- change the color and font-family for visibility
I wanna display multiple characters at the bottom of the frame
As has already been stated, you've overridden a method from the parent class, but failed to either take over it's responsibility or call it's super implementation (ie
paint).As a general recommendation, avoid overriding
paintof top level containers, likeJFrame, instead prefer overridingpaintComponentof normal containers, likeJPanel. Also see Painting in AWT and Swing and Performing Custom Painting to get a better understanding of how painting works in Swing.Further, avoid extending from top level containers, you're not adding any new functionality the class, instead prefer composition over extension. In particular,
JFramehas a complex component hierarchy, which could interfere with what ever was painted by thepaintmethod randomly.Also, in your current code, it would be possible for your paint to interfere with the label, you might want this, you might not, but it's a consideration to keep in mind.
The following example separates the label from the paint workflow, so it's not for the two to interfere with each other.