Guest User

Untitled

a guest
Apr 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import javax.swing.JButton;
  2. import javax.swing.JFrame;
  3. import java.awt.Canvas;
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.FlowLayout;
  7.  
  8. import java.awt.Graphics;
  9.  
  10. import java.awt.Rectangle;
  11. import java.awt.event.ActionEvent;
  12. import java.awt.event.ActionListener;
  13.  
  14. public class Zad2 extends JFrame{
  15.  
  16.     boolean selected;
  17.     Canvas canvas;
  18.     JFrame frame;
  19.    
  20.     public Zad2() {
  21.     frame = this;  
  22.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.     setLayout(new FlowLayout());
  24.     setPreferredSize(new Dimension(400,400));
  25.     canvas = getCanvas(75, 50);
  26.     canvas.setPreferredSize(new Dimension(390, 300));
  27.     add(canvas);
  28.     add(getButton());
  29.     pack();
  30.     setLocationRelativeTo(null);
  31.     }
  32.     /**
  33.     * Metoda obslugująca rysowanie
  34.     * x - pozycja x
  35.     * y - pozycja y
  36.     *
  37.     */
  38.     public Canvas getCanvas(final int x, final int y)
  39.     {
  40.     Canvas canvas = new Canvas()
  41.     {
  42.     private static final long serialVersionUID = 1L;
  43.     public void paint(Graphics g)
  44.     {
  45.     //rysowanie lini
  46.     Dimension d = getSize();
  47.     g.drawLine(0, 0, d.width, d.height);
  48.     g.drawLine(d.width, 0, 0, d.height);
  49.     //dodatki
  50.     if(selected)
  51.     {
  52.     setBackground(new Color(50, 100, 150));
  53.     g.drawString("Test Środowiska GUI", x, y); //75, 50
  54.     g.setColor(Color.blue);
  55.     g.fillOval(x+35, y+20, 50, 50);
  56.     g.setColor(Color.red);
  57.     g.drawRoundRect(x-10, y-20, 140, 30, 20, 20);
  58.     }
  59.     else
  60.     setBackground(new Color(255, 255, 255));
  61.     }
  62.     };
  63.     return canvas;
  64.     }
  65.     /**
  66.     * Przycisk rysowania/czyszczenia
  67.     *
  68.     */
  69.     public JButton getButton()
  70.     {
  71.     final JButton button = new JButton("Rysuj");
  72.     button.addActionListener(new ActionListener()
  73.     {
  74.     @Override
  75.     public void actionPerformed(ActionEvent e) {
  76.     if(selected==false)
  77.     {
  78.     selected=true;
  79.     button.setText("Czyść");
  80.     }
  81.     else
  82.     {
  83.     selected = false;
  84.     button.setText(" Rysuj ");
  85.     }
  86.     //odswiezenie
  87.     Rectangle rect = frame.getBounds();
  88.     canvas.repaint(rect.x, rect.y, rect.width, rect.height);
  89.     }
  90.     });
  91.     return button;
  92.     }
  93.     public static void main(String args[]){
  94.         new Zad2().setVisible(true);
  95.     }
  96. }
Add Comment
Please, Sign In to add comment