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); } });
setBackgroundissetBackgroundboth buttons are not selected. In general, why insetBackground, and not in somepenToggleButton.addItemListener? - zRrr