Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import java.awt.Canvas;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.Graphics;
- import java.awt.Rectangle;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- public class Zad2 extends JFrame{
- boolean selected;
- Canvas canvas;
- JFrame frame;
- public Zad2() {
- frame = this;
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLayout(new FlowLayout());
- setPreferredSize(new Dimension(400,400));
- canvas = getCanvas(75, 50);
- canvas.setPreferredSize(new Dimension(390, 300));
- add(canvas);
- add(getButton());
- pack();
- setLocationRelativeTo(null);
- }
- /**
- * Metoda obslugująca rysowanie
- * x - pozycja x
- * y - pozycja y
- *
- */
- public Canvas getCanvas(final int x, final int y)
- {
- Canvas canvas = new Canvas()
- {
- private static final long serialVersionUID = 1L;
- public void paint(Graphics g)
- {
- //rysowanie lini
- Dimension d = getSize();
- g.drawLine(0, 0, d.width, d.height);
- g.drawLine(d.width, 0, 0, d.height);
- //dodatki
- if(selected)
- {
- setBackground(new Color(50, 100, 150));
- g.drawString("Test Środowiska GUI", x, y); //75, 50
- g.setColor(Color.blue);
- g.fillOval(x+35, y+20, 50, 50);
- g.setColor(Color.red);
- g.drawRoundRect(x-10, y-20, 140, 30, 20, 20);
- }
- else
- setBackground(new Color(255, 255, 255));
- }
- };
- return canvas;
- }
- /**
- * Przycisk rysowania/czyszczenia
- *
- */
- public JButton getButton()
- {
- final JButton button = new JButton("Rysuj");
- button.addActionListener(new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent e) {
- if(selected==false)
- {
- selected=true;
- button.setText("Czyść");
- }
- else
- {
- selected = false;
- button.setText(" Rysuj ");
- }
- //odswiezenie
- Rectangle rect = frame.getBounds();
- canvas.repaint(rect.x, rect.y, rect.width, rect.height);
- }
- });
- return button;
- }
- public static void main(String args[]){
- new Zad2().setVisible(true);
- }
- }
Add Comment
Please, Sign In to add comment