I created a program in Java using JPanel and Graphics.
(我使用JPanel和Graphics在Java中创建了一个程序。)
This is simple Paint Panel program in which things draw when we drag mouse and when we want to make line with different color simply just press the button in a panel but the problem is that when I press a button in panel and drag the mouse whole components present in a panel turns into that color (Button' Color). (这是一个简单的“ Paint Panel”程序,当您拖动鼠标并想用不同的颜色绘制线条时,只需在面板上按一下按钮即可绘制内容,但问题是当我在面板上按一个按钮并拖动鼠标整个组件时面板中显示的颜色变为该颜色(“按钮”颜色)。)
Code:
(码:)
public class PaintAssign extends JPanel {
private ArrayList<Point> points= new ArrayList<>();
private ArrayList<Point> points2= new ArrayList<>();
public final JButton[] panelButton=new JButton[5];
public String[] colors={"RED","BLUE","GREEN","YELLOW","CYAN"};
int x=0;
public PaintAssign()
{ addMouseMotionListener(
new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e)
{
points.add(e.getPoint());
repaint();
}
});
addMouseListener(
new MouseAdapter(){
});
for (int i = 0; i < 5; i++) {
Rectangle r = new Rectangle(22, 22);
panelButton[i] = new JButton();
panelButton[i].setText(colors[i]);
panelButton[i].setOpaque(true);
panelButton[i].setBounds(r);
this.add(panelButton[i]);
this.setVisible(true);
}
mouseAction handle=new mouseAction();
panelButton[0].addActionListener(handle);
panelButton[1].addActionListener(handle);
panelButton[2].addActionListener(handle);
panelButton[3].addActionListener(handle);
panelButton[4].addActionListener(handle);
}
private class mouseAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==panelButton[0])
{
x=1;
}
else if(e.getSource()==panelButton[1])
{
x=2;
}
else if(e.getSource()==panelButton[2])
{
x=3;
}
else if(e.getSource()==panelButton[3])
{
x=4;
}
else if(e.getSource()==panelButton[4])
{
x=5;
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(x==0)
{
g.setColor(Color.BLACK);
}
else if(x==1)
{
g.setColor(Color.RED);
}
else if(x==2)
{
g.setColor(Color.BLUE);
}
else if(x==3)
{
g.setColor(Color.GREEN);
}
else if(x==4)
{
g.setColor(Color.YELLOW);
}else if(x==5)
{
g.setColor(Color.CYAN);
}
for(Point i:points)
{
g.fillOval(i.x,i.y,15,15);
}
}
ask by Abdullah Ikram translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…