2013-04-04 2 views
0

Im работает над очень простой программой. То, что я хочу сделать, - это добавить новый круг, когда нажимается firstButton (программа в настоящее время, так как это делается после того, как я уверен, что у меня есть правильные действия).Нарисуйте новые графические компоненты (например, круги), когда произойдет событие

Я знаю, что нужен метод paintComponent где-то, и, возможно, нужно использовать repaint, но не уверен, как поместить их в

Помощь будет признателен, спасибо:.

public class aGameForBella extends JPanel { 

    private int count1 = 0, count2 = 0, count3 = 0; 
    JButton firstButton, secondButton, thirdButton; 
    JLabel firstLabel, secondLabel, thirdLabel; 
    JPanel optionPanel; 

    //constructor method 
    public aGameForBella() { 
     //create components 
     optionPanel = new JPanel(); 
     firstButton = new JButton("Button option number one"); 
     firstLabel = new JLabel("You pushed the first button: " + count1 
       + " times"); 
     secondButton = new JButton("Button option number two"); 
     secondLabel = new JLabel("You pushed the second button: " + count2 
       + " times"); 
     thirdButton = new JButton("Button option number three"); 
     thirdLabel = new JLabel("You pushed the third button: " + count3 
       + " times"); 
     //add listeners 
     firstButton.addActionListener(new ButtonListener()); 
     secondButton.addActionListener(new ButtonListener()); 
     thirdButton.addActionListener(new ButtonListener()); 

     //add panels 
     add(optionPanel); 

     //add components to panels 
     optionPanel.add(firstButton); 
     optionPanel.add(firstLabel); 
     optionPanel.add(secondButton); 
     optionPanel.add(secondLabel); 
     optionPanel.add(thirdButton); 
     optionPanel.add(thirdLabel); 

     //set size of things 
     optionPanel.setPreferredSize(new Dimension(200, 200)); 
     setPreferredSize(new Dimension(250, 500)); 
     setBackground(Color.cyan); 

    } 

    //inner class 
    private class ButtonListener implements ActionListener { 
     public void actionPerformed(ActionEvent event) { 
      if (event.getSource() == firstButton) { 
       count1++; 
       firstLabel.setText("You pushed the first button: " + count1 
         + " times"); 
      } else if (event.getSource() == secondButton) { 
       count2++; 
       secondLabel.setText("And you pushed the second button: " 
         + count2 + " times"); 
      } else if (event.getSource() == thirdButton) { 
       count3++; 
       thirdLabel.setText("And the last button: " + count3 + " times"); 

      } 

     } 
    } 
} 
+2

Если вы ищете хороший учебный материал, я предлагаю лекции в standford (видео на youtube). Профессор довольно хорошо объясняет java, и есть большой кусок курса, посвященного графике. – didierc

ответ

2

В зависимости от ваших потребностей будет зависеть от вашего общего подхода.

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

В следующем примере в основном содержится список объектов на основе Shape и выполняется их перекраска каждый раз, когда компонент окрашивается.

enter image description here

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.Shape; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.geom.Ellipse2D; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class DrawCircles { 

    public static void main(String[] args) { 
     new DrawCircles(); 
    } 

    public DrawCircles() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       final CirclePane circlePane = new CirclePane(); 
       JButton btn = new JButton("Click"); 
       btn.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         circlePane.addCircle(); 
        } 

       }); 

       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(circlePane); 
       frame.add(btn, BorderLayout.SOUTH); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 

     }); 
    } 

    public class CirclePane extends JPanel { 

     private List<Shape> circles; 

     public CirclePane() { 
      circles = new ArrayList<>(25); 
     } 

     public void addCircle() { 
      int width = getWidth() - 1; 
      int height = getHeight() - 1; 
      int radius = (int) Math.round(Math.random() * (Math.min(width, height)/4f)); 
      int x = (int) Math.round(Math.random() * getWidth()); 
      int y = (int) Math.round(Math.random() * getHeight()); 
      if (x + radius > width) { 
       x = width - radius; 
      } 
      if (y + radius > height) { 
       y = height - radius; 
      } 
      circles.add(new Ellipse2D.Float(x, y, radius, radius)); 
      repaint(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      int width = getWidth() - 1; 
      int height = getHeight() - 1; 
      for (Shape shape : circles) { 
       g2d.draw(shape); 
      } 
      g2d.dispose(); 
     } 

    } 

} 
1

Custom Painting Approaches показаны два стандартных способа ведения заказную прорисовку. Первый - это сделать из списка, а второй - рисовать BufferedImage.

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