【发布时间】:2014-02-24 01:58:32
【问题描述】:
我正在制作一个小型绘画程序,它的左侧基本上有按钮,指示颜色,无论您在哪里单击和拖动,它都会使用图形绘制一个圆圈。我知道,根本没有效率,而且我可以使用笔画之类的东西,但我还在学习,还没有做到这一点,所以我用我所知道的来测试它。一切似乎都正常,只有一个小问题。我可以单击、拖动,然后绘制一条线。但是当我改变颜色,去画别的东西时,画的第一个圆圈是以前的颜色。我已经尝试了很多东西,但似乎无法修复它。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
public class painting extends JFrame{
ArrayList<Integer> mouseLocXList = new ArrayList<Integer>();
ArrayList<Integer> mouseLocYList = new ArrayList<Integer>();
ArrayList<Color> colors = new ArrayList<Color>();
Color colorChosen = Color.black;
String[] colorsSideBarButtonString = {"Red", "Blue", "Green", "Orange", "Pink"};
Color[] colorsSideBar = {Color.red, Color.blue, Color.green, Color.orange ,
Color.pink};
JButton[] buttons = new JButton[colorsSideBarButtonString.length];
public painting(){
setSize(1200,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setBackground(Color.WHITE);
setLayout(null);
setFocusable(true);
addMouseMotionListener(new handler());
colors.add(Color.black);
for(int x = 0; x < colorsSideBarButtonString.length; x++){
buttons[x] = new JButton(colorsSideBarButtonString[x]);
buttons[x].setBounds(2,(x*50)+30,70,46);
add(buttons[x]);
buttons[x].addActionListener(new buttonListener());
}
setVisible(true);
}
public static void main(String[] args){
new painting();
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.drawLine(72, 0, 72, 900);
g.drawLine(1150, 0, 1150, 900);
g.drawString("Colors", 17, 45);
for(int i = 0; i < mouseLocXList.size(); i++){
g.setColor(colors.get(i));
g.fillOval(mouseLocXList.get(i),mouseLocYList.get(i),30,30);
}
}
public class handler implements MouseMotionListener{
public void mouseDragged(MouseEvent e) {
mouseLocXList.add(e.getX());
mouseLocYList.add(e.getY());
colors.add(colorChosen);
repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
for(int c = 0; c < buttons.length; c++)
if(e.getSource() == buttons[c]){
colorChosen = colorsSideBar[c];
}
}
}
}
对不起,程序有点长,我看不出哪里可以缩短,一切似乎都是必要的。基本上每次单击和拖动鼠标时,它的位置都存储在一个数组中,然后在图形中的 for 循环中绘制。单击颜色并将其添加到自己的数组中,并且每次在拖动时更新鼠标位置,当前颜色都会添加到颜色数组中,因此可以在 for 循环中重新绘制颜色。我认为解决问题的最佳方法是运行它。
再一次,我知道这可能是你见过的最糟糕的书面程序之一。我明白,但我只是在测试并试图看看我能做到多先进。
【问题讨论】:
标签: java swing graphics jframe mouse