so I've been working on this drawing program using Java Swing and I've separated the Drawing Frame and Drawing Panel into separate classes.
I'm not sure why but when I start drawing, it gets very glitchy and a duplicate JSlider appears at the top
To make things more confusing, after I right click to select the colors and start drawing, a duplicate color selection screen appears at the top near the JSlider
For reference, here are the codes of the program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingFrame extends JFrame{
private Point mousePnt=new Point();
public static Color penColor = new Color(0,0,0);
private JSlider penSize = new JSlider(JSlider.HORIZONTAL,1,30,4);
public static int pen = 4;
DrawingFrame() {
JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.LEFT));
DrawingPanel jp = new DrawingPanel();
toolbar.add(new Label("Drag mouse to draw"));
toolbar.add(penSize);
this.add(toolbar,BorderLayout.SOUTH);
this.add(jp,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,600);
setVisible(true);
}
public static void main(String[] a){
new DrawingFrame();
}
public class DrawingPanel extends JPanel implements MouseMotionListener, MouseListener, ChangeListener {
public DrawingPanel(){
addMouseMotionListener(this);
addMouseListener(this);
penSize.addChangeListener(this);
setBackground(Color.white);
}
public void mouseMoved (MouseEvent me){
}
public void mouseDragged(MouseEvent me) {
mousePnt = me.getPoint();
repaint();
}
public void mouseClicked(MouseEvent me) {
if(me.getModifiers()== MouseEvent.BUTTON3_MASK){
penColor = JColorChooser.showDialog(null,"Change pen colour",penColor);
}
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) { }
public void mousePressed(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) { }
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
pen = (int)source.getValue();
}
}
@Override
public void paintComponent(Graphics g){
//g.setStroke(new BasicStroke(pen));
g.setColor(penColor);
g.fillOval(mousePnt.x,mousePnt.y,pen,pen);
}
}
}
Following the comments, I added super.paintComponent(g); under paintComponent
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(penColor);
g.fillOval(mousePnt.x,mousePnt.y,pen,pen);
}
However, this presented a new problem where the gui worked perfectly to change sizes and color but now nothing happens when I try to draw. Instead it only shows a single circle everytime I left click