2017-04-20 3 views
0

그래서 내 드로잉 패널을 지우려고하는데 여러 예제를 살펴 보았지만 그 중 아무 것도 나를 위해 작동하지 않는 것 같습니까? 필자는 완벽하게 작동해야하는 텍스트 필드/오류를 지우는 명확한 단추가 있지만 그리기 패널은 여전히 ​​arraylists 또는 "다시 그리기"를 지우지 않습니다. 타원 크기를 바꾸면서 놀고 있으니 drawPoint 메서드를 무시하십시오. 당신은 당신의 메인 클래스에서이의 mousePressed 방법이Repainting JPanel

public class Panel extends JPanel{ 
ArrayList<Point> pointArray = new ArrayList<>(); 
ArrayList<Color> colorArray = new ArrayList<>(); 

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    repaint(); 
    //Create the 2D graphics object 
    Graphics2D myDrawing = (Graphics2D) g; 
    for (int i = 0; i < pointArray.size(); i++) { 
     myDrawing.setColor(colorArray.get(i)); 
     myDrawing.fillOval(pointArray.get(i).x,pointArray.get(i).y, 10, 10); 
    }   
} 
    public void drawPoints(int mouseX, int mouseY, int height, int width){ 
    Point p = new Point(mouseX,mouseY); 
    pointArray.add(p); 
    colorArray.add(this.getForeground()); 
    repaint(); 
} 

    public void changeColor(){ 
int red = (int) (Math.random() * 256); 
int green = (int) (Math.random() * 256); 
int blue = (int) (Math.random() * 256); 
this.setForeground(new Color(red,green,blue)); 
} 

public void mousePressed(MouseEvent event) { 
    pointArray.clear(); 
    colorArray.clear(); 
    repaint(); 
} 

} 

public static void main(String[] args) { 
    //set the frame 
    JFrame frame = new JFrame(); 
    frame.setSize(600, 300); 
    frame.setTitle("Multiple Panels"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //create the panel for GUI 
    JPanel panelGUI = new JPanel(); 
    panelGUI.setBackground(Color.yellow); 
    //GUIs 
    //create textfields 
    JTextField radiusField1 = new JTextField("10", 10); 
    JTextField radiusField2 = new JTextField("10", 10); 
    //create buttons 
    final JButton clearDrawingButton = new JButton("Clear Screen"); 
    final JButton changeColorButton = new JButton("Change Color"); 
    //labels 
    final JLabel displayLabel = new JLabel(""); 

    //add all GUIs to the GUI panel 
    panelGUI.add(radiusField1); 
    panelGUI.add(radiusField2); 
    panelGUI.add(changeColorButton); 
    panelGUI.add(clearDrawingButton); 
    panelGUI.add(displayLabel); 

    //create the panel to draw 
    final Panel drawingPanel = new Panel(); 
    drawingPanel.setBackground(Color.white); 
    //create the initial color 
    Color drawingColor = new Color(255,0,0); 
    //set the initial drawing color of the panel 
    drawingPanel.setForeground(drawingColor); 

    //add the grid with two columns and two rows to add the three panels 
    GridLayout grid = new GridLayout(0,2,10,20); 
    //add the grid to the frame 
    frame.setLayout(grid); 
    //add the panels to the frame 
    frame.add(panelGUI); 
    frame.add(drawingPanel); 


class MouseClickListener implements MouseListener 
    { 
     public void mouseClicked(MouseEvent event) 
     { 
      int x = event.getX(); 
      int y = event.getY(); 
      System.out.println(x + " " + y);    

      try { 
      String text1 = radiusField1.getText(); 
      String text2 = radiusField2.getText(); 
      int height = Integer.parseInt(text1); 
      int width = Integer.parseInt(text2); 
      drawingPanel.drawPoints(x, y, height, width); 

     } catch (NumberFormatException ex) { 
     displayLabel.setText("Textfields empty! Please enter number.");} 
     } 

     // Do­nothing methods 
     public void mouseReleased(MouseEvent event) {} 
     public void mousePressed(MouseEvent event) {} 
     public void mouseEntered(MouseEvent event) {} 
     public void mouseExited(MouseEvent event) {} 
     } 
    class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      if (event.getSource()== changeColorButton){ 
       drawingPanel.changeColor(); 
      } 

      if(event.getSource()==clearDrawingButton){ 
       radiusField1.setText("10"); 
       radiusField2.setText("10"); 
       displayLabel.setText(""); 
      } 
     } 
    } 
    MouseListener listener1 = new MouseClickListener(); 
    drawingPanel.addMouseListener(listener1); 
    ActionListener listener = new ButtonListener(); 
    changeColorButton.addActionListener(listener); 
    clearDrawingButton.addActionListener(listener); 
    frame.setVisible(true); 
} 

} 
+0

paintComponent() 메소드에서 repaint()을 호출하지 마십시오. 이것에 의해, 컴퍼넌트는 그 자체를 계속 칠하기 (위해)됩니다. – camickr

답변

0

나는 명확한 텍스트 필드를 클리어 버튼/I가 완벽하게 작동있어 오류가 있지만이 그리기 패널이 아직 클리어하지 않는다 arraylists 또는 "다시 칠해".

음 텍스트 필드를 지 웁니다 코드를 살펴 :

 if(event.getSource()==clearDrawingButton){ 
      radiusField1.setText("10"); 
      radiusField2.setText("10"); 
      displayLabel.setText(""); 
     } 

어디에 ArrayLists를 지 웁니다 코드?

Arraylist를 지우는 코드를 ActionListener에 추가하십시오.

"직사각형"을 그리는 작업 코드에 대해서는 Custom Painting Approaches을 확인할 수도 있습니다. 다른 색상과 "지우기"버튼을 지원합니다.

또한 타원형 크기에 JTextField를 사용하는 대신 JSpinner을 사용하는 것이 좋습니다. 이렇게하면 사용자가 쉽게 숫자 값을 변경할 수 있으며 입력 한 값이 숫자인지 확인하기 위해 특별한 편집을 할 필요가 없습니다.

0

:

public void mousePressed(MouseEvent event) { 
    pointArray.clear(); 
    colorArray.clear(); 
    repaint(); 
} 

을하지만 당신의 메인 클래스는 더의 MouseListener 및 구현하지 않기 때문에 그것은 아무것도 안하고 여기

내 코드입니다 하나는이 메소드를 호출합니다.

나머지 코드는별로 보이지 않습니다. 나는 당신이 코스의 일부로 이것을하고 있다고 가정합니다. 그렇지 않으면 비 - 직장 환경에서 Java Swing을 배우려고합니다. 이것이 사실이라면 최소한 MouseListeners로 다시 시작하고 AbstractAction을 서브 클래 싱하고 JButton.setAction (myAction)과 함께 사용하여 버튼 응답에 대한 액션을 생성하는 것이 좋습니다. 이 지금 고통스러운 것처럼 보일 수 있지만, 당신은 미래에 그것을했다 드리겠습니다