Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mloeschl8_2;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionListener;
- import java.awt.event.*;
- import java.awt.Color;
- public class RechteckPanel extends JPanel{
- private JButton löschen, einRechteck, zehnRechtecke;
- private RechteckZeichnung grafik;
- /**
- *
- */
- public RechteckPanel(){
- this.setLayout(new BorderLayout());
- grafik = new RechteckZeichnung(0);
- this.add(grafik);
- JPanel oben = new JPanel(new GridLayout(1, 3));
- löschen = new JButton("Löschen");
- oben.add(löschen);
- einRechteck = new JButton("1 Rechteck");
- oben.add(einRechteck);
- zehnRechtecke = new JButton("10 Rechtecke");
- oben.add(zehnRechtecke);
- this.add(oben, BorderLayout.PAGE_START);
- ActionHandler ah = new ActionHandler();
- löschen.addActionListener(ah);
- einRechteck.addActionListener(ah);
- zehnRechtecke.addActionListener(ah);
- }
- private class ActionHandler implements ActionListener{
- @Override
- public void actionPerformed(ActionEvent e){
- if(e.getSource() == löschen){
- grafik.hide();
- } else if(e.getSource() == einRechteck){
- grafik.show();
- //X
- grafik.setBereichA(getWidth());
- grafik.setX();
- //Y
- grafik.setBereichB(getHeight());
- grafik.setY();
- grafik.setFarbe();
- } else if(e.getSource() == zehnRechtecke){
- show();
- grafik.setAnzahl(10);
- }
- }
- }
- }
- package mloeschl8_2;
- import javax.swing.*;
- import java.awt.*;
- public class RechteckZeichnung extends JPanel{
- private Color farbe ;
- private int x, y;
- private int a = 20;
- private int bereich;
- private int anzahl;
- public void setAnzahl(int anzahl) {
- this.anzahl = anzahl;
- super.repaint();
- }
- public RechteckZeichnung(int anzahl){
- this.anzahl = anzahl;
- }
- public Color generateColor(){
- int r, g, b;
- r = (int)(Math.random() * 256);
- g = (int)(Math.random() * 256);
- b = (int)(Math.random() * 256);
- Color back = new Color(r, g, b);
- return back;
- }
- public int generatePositionX(){
- int back = (int)(Math.random() * this.bereich);
- return back;
- }
- public void setX(){
- this.x = generatePositionX();
- }
- public void setFarbe(){
- this.farbe = generateColor();
- this.repaint();
- }
- public void setY(){
- this.y = generatePositionX();
- }
- public void setBereichA(int a){
- this.bereich = a;
- }
- public void setBereichB(int a){
- this.bereich = a;
- }
- @Override
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- if(this.anzahl != 0) {
- for (int i = 0; i < this.anzahl; i++) {
- setBereichA(getWidth());
- setX();
- //Y
- setBereichB(getHeight());
- setY();
- setFarbe();
- g.setColor(this.farbe);
- g.fillRect(x, y, a, a);
- }
- }else{
- g.setColor(this.farbe);
- g.fillRect(x, y, a, a);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement