There are 2 mutually exclusive togglebtn on the form (by pressing one I activate the "pencil" mode, by pressing the second I activate the "line" mode). To draw arbitrary images, I created the PaintPanel class inheritor from JPanel , and placed 2 classes in it: MyMouseHandler (draws with a pencil) and DrawLine (draws lines) the heirs from MouseAdapter. In the overridden setBackground method of the PaintPanel class, I create instances of the 2 drawing classes listed above and, through the conditions, try to select the appropriate argument by pressing the corresponding button ... Does not work ...

public class PaintPanel extends JPanel { @Override public void setBackground(Color bg) { super.setBackground(BACK_COLOR); setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT)); handler = new MyMouseHandler(); lineHandler = new DrawLine(); if (penToggleBtn.isSelected()) { this.addMouseListener(handler); this.addMouseMotionListener(handler); } if (lineToggleBtn.isSelected()) { this.addMouseListener(lineHandler); this.addMouseMotionListener(lineHandler); } } 

If I comment on one of the conditions, and with the rest I remove if , it works. Tell me how to implement this idea?

Sample code with addItemListener

 penToggleBtn = new JToggleButton("P"); penToggleBtn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { brushPanel.addMouseListener(handler); brushPanel.addMouseMotionListener(handler); } }); lineToggleBtn = new JToggleButton("Line"); lineToggleBtn.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { brushPanel.addMouseListener(lineHandler); } }); 
  • And you use the debugger to see what happens in this method. - post_zeew
  • I suppose that at the moment when setBackground is setBackground both buttons are not selected. In general, why in setBackground , and not in some penToggleButton.addItemListener ? - zRrr
  • @zRrr, I also tried it. When launching the application, the penToggleButton button is already pressed by default; activated pencil drawing mode. Next, I switch to the "line" button, and everything seems to be normal, another drawing mode is activated, but it does not work as it should (draws a line and arbitrarily and somehow in general + coordinate output to the console), and if I return to " a pencil ", then drawing becomes a pencil, but the mode of printing coordinates to the console from the button" line "does not turn off, and the last pixel of the color remains from the line mode ... - Tim Leyden
  • example added above - Tim Leyden

0