dimanche 10 mai 2015

ungewünschter Nebeneffekt bei der repaint() Methode

Hi,
wie kann ich den "Fehler" beheben?
Und falls euch zufällig noch schlechte programmierter Code auffällt könnt ihr das gerne sagen. Einfach mal ausführen und auf den Button klicken. Dann wisst ihr was ich meine ;)
Danke schonmal im Vorraus

Java Code:

  1. package teste;
  2.  
  3.  
  4.  
  5. import java.awt.*;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8.  
  9. import javax.swing.*;
  10.  
  11. public class MainFrame extends JFrame {
  12. private InputPanel input;
  13. private OutputPanel output;
  14.  
  15.  
  16. MainFrame(){
  17. super("ButtonTest");
  18. this.setSize(400, 400);
  19. this.setLocationByPlatform(true);
  20. this.setLayout(new GridLayout(3,1));
  21. this.setVisible(true);
  22. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23. input = new InputPanel();
  24. output = new OutputPanel();
  25. this.add(output);
  26. this.add(input);
  27. this.add(new Label("Hallo"));
  28. input.addActionListener(new SoneAktion());
  29. }
  30.  
  31. private class SoneAktion implements ActionListener{
  32.  
  33. @Override
  34. public void actionPerformed(ActionEvent ae) {
  35. output.farbe(Color.blue);
  36. output.repaint();
  37.  
  38.  
  39. }
  40.  
  41. }
  42. public static void main(String[]args){
  43. new MainFrame();
  44. }
  45. }

Java Code:

  1. package teste;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.ActionListener;
  5.  
  6. import javax.swing.*;
  7.  
  8. public class InputPanel extends JPanel {
  9. private JButton button;
  10.  
  11. InputPanel(){
  12. this.setLayout(new FlowLayout());
  13. button = new JButton("Change colour");
  14. button.setSize(100, 100);
  15. this.add(button);
  16.  
  17. }
  18.  
  19. public void addActionListener(ActionListener al){
  20. button.addActionListener(al);
  21. }
  22.  
  23. }

Java Code:

  1. package teste;
  2.  
  3. import java.awt.*;
  4. import javax.swing.*;
  5.  
  6. public class OutputPanel extends JPanel {
  7. Color c = Color.white;
  8.  
  9. OutputPanel(){
  10. this.setLayout(new FlowLayout());
  11.  
  12. }
  13.  
  14. public void paintComponent(Graphics g) {
  15.  
  16.  
  17. g.setColor(this.c);
  18. g.drawOval(getWidth()/2-10, getHeight()/4, 20, 20);
  19. g.fillOval(getWidth()/2-10, getHeight()/4, 20, 20);
  20. }
  21.  
  22. public Color farbe(Color c){
  23. this.c = c;
  24. return c;
  25. }
  26. }


ungewünschter Nebeneffekt bei der repaint() Methode

0 commentaires:

Enregistrer un commentaire