Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class Simple2DApp {
- private static Rectangle r1, r2;
- private static JPanel drawPanel;
- public static void main(String[] args) {
- r1 = new Rectangle(30, 20, 60, 30);
- r2 = new Rectangle(360, 130, 120, 205);
- JFrame mainFrame = new JFrame("Easy 2D Java App");
- mainFrame.setBounds(50, 50, 800, 600);
- mainFrame.setLayout(null);
- drawPanel = new MyPanel(Color.red, Color.blue);
- drawPanel.setBounds(20, 20, 750, 420);
- drawPanel.setBackground(Color.white);
- ActionListener listener = new MyActionListener();
- Button increaseBut = new Button("Increase");
- increaseBut.setActionCommand("increase");
- increaseBut.addActionListener(listener);
- increaseBut.setBounds(30, 510, 100, 35);
- Button decreaseBut = new Button("Decrease");
- decreaseBut.setActionCommand("decrease");
- decreaseBut.addActionListener(listener);
- decreaseBut.setBounds(160, 510, 100, 35);
- Button switchBut = new Button("Switch");
- switchBut.setActionCommand("switch");
- switchBut.addActionListener(listener);
- switchBut.setBounds(300, 510, 100, 35);
- mainFrame.add(drawPanel);
- mainFrame.add(increaseBut);
- mainFrame.add(decreaseBut);
- mainFrame.add(switchBut);
- mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- mainFrame.setVisible(true);
- }
- private static class MyPanel extends JPanel {
- private final Color r1Color, r2Color;
- public MyPanel(Color r1Color, Color r2Color) {
- this.r1Color = r1Color;
- this.r2Color = r2Color;
- }
- public void paint(Graphics g) {
- super.paint(g);
- g.setColor(r1Color);
- g.fillRect(r1.x, r1.y, r1.width, r1.height);
- g.setColor(r2Color);
- g.fillRect(r2.x, r2.y, r2.width, r2.height);
- }
- }
- private static class MyActionListener implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- if(e.getActionCommand().equals("increase")) {
- r1.height += 2;
- r1.width += 2;
- r1.x--;
- r1.y--;
- r2.height += 2;
- r2.width += 2;
- r2.x--;
- r2.y--;
- }
- else if(e.getActionCommand().equals("decrease")) {
- r1.height -= 2;
- r1.width -= 2;
- r1.x++;
- r1.y++;
- r2.height -= 2;
- r2.width -= 2;
- r2.x++;
- r2.y++;
- }
- else if(e.getActionCommand().equals("switch")) {
- Rectangle buff = r1;
- r1 = r2;
- r2 = buff;
- }
- drawPanel.repaint();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement