从静态上下文错误

时间:2015-04-28 01:15:49

标签: java object arraylist static non-static

我想说这个问题很可能是重复的,但我不确定究竟是什么问题:由于这个原因,我无法进行正确的搜索。

我目前正在研究Java中的绘画程序。我正在尝试存储在Shape对象的ArrayList中绘制形状的指令。我也使用MouseListener来获取坐标。

目标是当按下鼠标时,它会记录该点。当它被释放时,它会保留第二个点的记录,然后将两个坐标发送到构造函数的行history.add(new Shape(x,y,x2,y2))。

相关代码如下:

// Create an ArrayList for the History
static ArrayList history = new ArrayList(0);

.
.
.

// Co-ordinates for rectangle painting
static int x = 0;
static int y = 0;
static int x2 = 0;
static int y2 = 0;

.
.
.

/**
 * A class for handling mouse input
 * 
 * All methods within the MouseHandler class MUST be there
 * If not, the code will not compile.
 */
private static class MouseHandler implements MouseListener
{
    public void mousePressed(MouseEvent e) {
        x = e.getX();
        y = e.getY();
    }

    public void mouseReleased(MouseEvent e) {
        x2 = e.getX();
        y2 = e.getY();

        //repaint() is a special method that must be called to "repaint"
        //your shapes on the screen. 
        canvas.repaint();
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
        // Create a new shape on the button unclick
        history.add(new Shape(x, y, x2, y2));
    }
}

此代码在行history.add(new Shape(x,y,x2,y2))中抛出异常; :“非静态方法,这不能从静态上下文中引用。”该错误似乎特别引用(new Shape(x,y,x2,y2))。我不明白为什么这种方法是非静态的。

提前非常感谢任何帮助, Placowdepuss

编辑:这是我的完整代码:

//Import packages needed

// For the GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 

// For the ArrayList
import java.util.*;

/**
* A simple drawing application.
* 
* @author (Massimo A. Lipari) 
* @version (1.0.0)
*/
public class PaintProgram
{
// Create the frame and the panels for the GUI
static JFrame frame = new JFrame("PaintIt");
static JPanel panel = new JPanel();
static JPanel buttonPanel = new JPanel();
static MyPanel canvas = new MyPanel();

static JLabel sampleText = new JLabel("Label");

// Create an array for the buttons
static JButton[] buttonArray = new JButton[12];

// Create an ArrayList for the History
static ArrayList<Shape> history = new ArrayList<Shape>();

// Co-ordinates for rectangle painting
static int x, y, x2, y2;

// Create a variable for keeping track of the active tool
static String activeTool;

// Variables for holding the current colour and fill settings
static boolean currentFill;
static Color currentColour;

public static void main(String[] args)
{        
    // Set the frame size
    frame.setSize(1920,1040);

    // Create the mouse listeners
    canvas.addMouseListener(new MouseHandler());

    // Set the size for the canvas portion of the screen
    canvas.setSize(1920, 880);

    // Add panels to frame

    // Set layout for panel
    panel.setLayout(new BorderLayout());

    createButtonPanel();
    panel.add(buttonPanel, BorderLayout.NORTH);
    panel.add(canvas, BorderLayout.CENTER);
    frame.getContentPane().add(panel);

    // Set frame to visible and allows it to exit on closing of the frame
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void createButtonPanel()
{
    // Set the buttonPanel size, and creates a grid layout for it
    buttonPanel.setSize(1920, 160);

    buttonPanel.setLayout(new GridLayout(1, 12));

    // Initialize the buttons
    for (int i = 0; i < buttonArray.length; i++) {
        buttonArray[i] = new JButton("Button " + (i + 1));

        // Create and add a button handler
        buttonArray[i].addActionListener(new ButtonHandler());

        buttonArray[i].setIcon(new ImageIcon("icon" + i + ".png"));
        buttonArray[i].setBackground(Color.WHITE);

        buttonPanel.add(buttonArray[i]);
    }
}

/**
 * A class for handling button input (the tools) 
 */
private static class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == buttonArray[0]) {
            buttonArray[0].setBackground(JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground()));
        } else if (e.getSource() == buttonArray[1]) {
            currentFill = true;
            buttonArray[1].setBackground(Color.LIGHT_GRAY);
            buttonArray[2].setBackground(null);
        } else if (e.getSource() == buttonArray[2]) {
            currentFill = false;
            buttonArray[1].setBackground(null);
            buttonArray[2].setBackground(Color.LIGHT_GRAY);
        } else if (e.getSource() == buttonArray[3]) {
            activeTool = "paint";
        } else if (e.getSource() == buttonArray[4]) {
            activeTool = "rectangle";
        } else if (e.getSource() == buttonArray[5]) {
            activeTool = "triangle";
        } else if (e.getSource() == buttonArray[6]) {
            activeTool = "circle";
        } else if (e.getSource() == buttonArray[7]) {
            activeTool = "line";
        } else if (e.getSource() == buttonArray[8]) {
            activeTool = "text";
        } else if (e.getSource() == buttonArray[9]) {

        } else if (e.getSource() == buttonArray[10]) {

        } else if (e.getSource() == buttonArray[11]) {

        }
    }
}

/**
 * A class for handling mouse input
 * 
 * All methods within the MouseHandler class MUST be there
 * If not, the code will not compile.
 */
private static class MouseHandler implements MouseListener
{
    public void mousePressed(MouseEvent e) {
        x = e.getX();
        y = e.getY();
    }

    public void mouseReleased(MouseEvent e) {
        x2 = e.getX();
        y2 = e.getY();

        //repaint() is a special method that must be called to "repaint"
        //your shapes on the screen. 
        canvas.repaint();
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
        // Create a new shape on the button unclick
        history.add(new Shape(x, y, x2, y2));
    }
}

/**
 * A class for painting the shapes
 */
private static class MyPanel extends JPanel
{
    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
        setBackground(Color.white);
    }

    public Dimension getPreferredSize() {
        return new Dimension(600,600); 
    }

    // ALL drawing of shapes must be done in the paintComponent method
    public void paintComponent(Graphics g) {

        super.paintComponent(g);       

        //Drawing a basic rectangle from top left corner to bottom right on canvas
        if (x2 >= x && y2 >= y)
            g.drawRect(x, y, x2 - x, y2 - y);
        else if (x2 >= x && y2 <= y)
            g.drawRect(x, y2, x2 - x, y - y2);
        else if (x2 <= x && y2 >= y)
            g.drawRect(x2, y, x - x2, y2 - y);
        else if (x2 <= x && y2 <= y)
            g.drawRect(x2, y2, x - x2, y - y2);
    }
}

/**
 * A class that creates a colour picker
 * 
 * This code is the property of Oracle Systems Inc. It is copyrighted.
 */
static class ColorChooser_01 extends JFrame
{
    public static void main(String[] args) {
        new ColorChooser_01();
    }

    public ColorChooser_01() {
        this.setSize(300, 100);
        JPanel panel1 = new JPanel();
        sampleText.setBackground(null);
        panel1.add(sampleText);

        this.add(panel1);
        this.setVisible(true);
    }

    public class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) {
            Color c = JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground());
            if (c != null){
                sampleText.setForeground(c);
                buttonArray[0].setBackground(c);
            }
            else{
                sampleText.setForeground(Color.WHITE);
            }
        }
    }
}

/**
 * A class for creating objects of type Shape
 */
public class Shape
{
    // Variable for storing the type of shape
    String type;

    // Initialize variables for storing points for shape creation
    int xcoord;
    int ycoord;
    int xcoord2;
    int ycoord2;

    // Boolean variable to control whether the shape is filled or not -- defaults to false
    boolean fill = false;

    // Variable to hold the coulour
    Color colour;

    public Shape(int newX, int newY, int newX2, int newY2)
    {
        type = activeTool;

        xcoord = newX;
        ycoord = newY;
        xcoord2 = newX2;
        ycoord2 = newY2;

        fill = currentFill;
        colour = currentColour;
    }

    public String getType()
    {
        return type;
    }

    public int getX()
    {
        return xcoord;
    }

    public int getY()
    {
        return ycoord;
    }

    public int getX2()
    {
        return xcoord2;
    }

    public int getY2()
    {
        return ycoord2;
    }

    public boolean getFill()
    {
        return fill;
    }

    public Color getColour()
    {
        return colour;
    }
}
}

1 个答案:

答案 0 :(得分:0)

您需要将shape类移动到另一个文件,因为在同一个文件中不能有两个公共类