因此,我的目標是使用GUI製作一個基本的Etch-A-Sketch。除了能夠使用鼠標進行繪製外,我還需要添加一個按鈕,以改變任何四種顏色之間的線條顏色。正如我剛剛學習這是第一次,我得到儘可能改變線的顏色之前,我遇到了一個問題:Java:不知道如何修改一個單獨的類中的圖形對象
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Etch_A_Sketch implements MouseListener, MouseMotionListener
{
JFrame window;
Container content;
int mouseX,mouseY,oldX,oldY;
JButton colorButton;
ActionListener bPress = new MyListener();
public Etch_A_Sketch()
{
JFrame window = new JFrame("Classic Etch a Sketch");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = window.getContentPane();
window.setSize(640,480);
content.setLayout(new FlowLayout());
content.addMouseListener(this);
content.addMouseMotionListener(this);
colorButton = new JButton("Click to switch color!");
colorButton.setSize(175,50);
colorButton.setVisible(true);
colorButton.addActionListener(bPress);
content.add(colorButton);
window.setVisible(true);
}
public void mouseClicked(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
//repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
//repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
//repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
//repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
if (oldX ==0)
{
oldX=mouseX;
oldY=mouseY;
return;
}
Graphics g = content.getGraphics(); // use g to draw onto the pane
g.drawLine(oldX,oldY, mouseX, mouseY);
oldX = mouseX;
oldY = mouseY;
// repaint();
}
public void mouseMoved(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
//repaint();
}
class MyListener implements ActionListener
{
final Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE};
int index = 0;
public void actionPerformed(ActionEvent e)
{
g.setColor(colors[index]);
index = (index + 1) % colors.length;
}
}
public static void main(String[] args)
{
new Etch_A_Sketch();
}
}
我的問題是這樣的 - 我實現了所提到的「G」在MyListener類中超出範圍,因爲它是mouseDragged方法的一部分。當我的JButton被按下時,我將如何去改變它?我已經嘗試將g的聲明移到方法之外,但它不起作用。任何幫助,將不勝感激!另外,可能值得注意的是我有一個基本文件來啓動這個項目,並且「// repaint();」線已經分開了。我不確切地知道他們的意思,但是......這與我的問題有關嗎?
介紹靜態變量,尤其是包含*圖形上下文*的靜態變量可能是一個非常糟糕的主意。例如,如果你這樣做,你認爲會發生什麼:'new Etch_A_Sketch();新的Etch_A_Sketch();'?第一個蝕刻草圖上的圖紙繪製在第二個窗口上! – cubrr