2015-04-28 3 views
-1

Я хочу сказать, что этот вопрос очень возможно дубликат, но я точно не знаю, в чем проблема: я не могу выполнить правильный поиск, потому что этого.Нестатическая переменная Java, связанная с ошибкой статического контекста

В настоящее время я работаю над программой рисования на Java. Я пытаюсь сохранить инструкции для рисования фигур в объектах ArrayList of Shape. Я также использую MouseListener для получения координат.

Цель состоит в том, что при нажатии мыши она сохраняет запись этой точки. Когда он отпущен, он сохраняет запись этой второй точки, затем отправляет две координаты в конструктор в строке history.add (новая 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 (новая форма (х, у, х2, y2)); : «Нестатический метод, на который нельзя ссылаться из статического контекста». Вероятно, ошибка ссылается (новая форма (x, y, x2, y2)). Я не понимаю, почему этот метод будет нестационарным.

Любая помощь очень ценится заранее, Placowdepuss

Edit: Вот мой полный код:

//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; 
    } 
} 
} 
+0

Я не понимаю, почему весь ваш код статичен. –

+0

Да, почему ваш код статичен и не должен быть объявленными переменными в MouseHandler? – TameHog

+0

Как определяется форма? –

ответ

0

Вы должны переместить класс формы в другой файл, потому что вы не можете иметь два общественных классов в том же файле

+0

Извините, если это не было ясно, но ArrayList используется несколькими классами. Существует основной класс PaintProgram, а MouseHandler - это класс внутри него. Кроме того, по какой-то причине это не решило проблему. Я отредактирую свой пост, чтобы показать весь код. – Placowdepuss

+0

Тогда просто укажите его как 'mouseHandlerInstance.history' – TameHog

+0

То же самое с другими vars – TameHog

Смежные вопросы

 Смежные вопросы