我正在尝试通过MouseEventClicked从JColorChooser中选择一种颜色,然后将所选颜色设置为penColor但由于某种原因它无法正常工作。我想我在MouseClicked函数中有问题。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
@SuppressWarnings("serial")
public class Paint3<penColor> extends JFrame implements MouseMotionListener, MouseListener, ChangeListener {
int size = 2;
private Point pt = new Point();
private JSlider penSize = new JSlider(JSlider.VERTICAL,1,10,3);
JColorChooser jc = new JColorChooser();
public Color penColor = new Color(0,0,0);
public JPanel DrawingPanel = new JPanel(){
public void paint(Graphics g){
g.fillOval((int) pt.getX(), (int)pt.getY(), 5,5);
}
};
public Paint3(){
super("My Painter");
Label l1 = new Label("Drag Mouse To Draw");
JPanel jp2 = new JPanel();
this.add((DrawingPanel), BorderLayout.NORTH);
DrawingPanel.add((l1),BorderLayout.NORTH);
this.add((jp2),BorderLayout.SOUTH);
jp2.add(jc);
this.addMouseMotionListener(this);
this.addMouseListener(this);
this.add(penSize, BorderLayout.EAST);
penSize.addChangeListener((ChangeListener) this);
penSize.setMinorTickSpacing(1);
penSize.setPaintTicks(true);
setSize(700,700);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void mouseDragged(MouseEvent me){
Graphics2D g = (Graphics2D)getGraphics();
g.setStroke(new BasicStroke(size));
g.setColor(penColor);
g.drawLine(pt.x,pt.y, me.getX(), me.getY());
pt = me.getPoint();
}
@Override
public void mouseMoved(MouseEvent me){
pt = me.getPoint();
}
@Override
public void mouseClicked(MouseEvent me){
if(me.getModifiers()== MouseEvent.BUTTON3_MASK){
//penColor = jc; //(this, "Change Pen Color" , penColor);
//penColor = jc.getColor();
penColor = jc.getColor();
}
}
@Override
public void mouseEntered(MouseEvent me){}
@Override
public void mouseExited(MouseEvent me){}
@Override
public void mousePressed(MouseEvent me){}
@Override
public void mouseReleased(MouseEvent me){}
@Override
public void stateChanged(ChangeEvent me){
JSlider source = (JSlider)me.getSource();
if(!source.getValueIsAdjusting()){
size = (int)source.getValue();
}
}
public static void main(String[] args){
new Paint3();
}
}
答案 0 :(得分:0)
好吧,试试这段代码:
@Override
public void mousePressed(MouseEvent me){
penColor = jc.getColor();
}
您将修改 mousePressed 中的颜色,而不是 mouseClicked
中的颜色我希望它会帮助你,最好的问候
答案 1 :(得分:0)
这不是这样做的方法。 MouseListener
对javax.swing.JColorChooser
的预期方式不起作用。 Alteast不像你在帖子中提到的那样。
您需要导入javax.swing.colorchooser.ColorSelectionModel
并为其添加javax.swing.ChangeListener
。
JColorChooser jc = new JColorChooser();
ColorSelectionModel model = jc.getSelectionModel();
model.addChangeListener(
@Override
public void stateChanged(ChangeEvent event) {
penColor = jc.getColor();
}
);