import javax.swing.*; import java.awt.*; public class Car { public static void main(String[] args) { SwingApp app = new SwingApp(300, 300); // set app window size app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class SwingApp extends JFrame { private final DrawPanel panel; // class variable public SwingApp(int width, int height) // class constructor { super(); // call to super class constructor Container pane = super.getContentPane(); // create layout, set colors panel = new DrawPanel(); // add GUI components panel.setBackground(Color.yellow); pane.add(panel); Toolkit toolkit = Toolkit.getDefaultToolkit(); // optionally position JFrame Dimension screenSize = toolkit.getScreenSize(); // in the middle of the screen super.setLocation((screenSize.width - width)/2, (screenSize.height - height)/2); super.setTitle("Swing app"); // set desired window title super.setSize(width, height); // set desired window size super.setVisible(true); // add here more code for GUI components } } class DrawPanel extends JPanel // main window panel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); // must be the 1st line // add here more code for drawing on panel // setting background and foreground colors g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.red); // drawing the car body g.fillRect(100,110, 60, 10); // drawing the wheels g.setColor(Color.black); g.fillOval(110, 120, 10, 10); // left wheel g.fillOval(140, 120, 10, 10); // right wheel int x[] = {110, 120, 140, 150}; // coordinate arrays for the int y[] = {110, 100, 100, 110}; // car cabin g.setColor(Color.blue); g.fillPolygon(x, y, 4); // drawing the cabin in blue g.drawString("how do you like it?", 80, 90); } } |