I have two graphics methods in my program. One for the menu and one for the game. I have previously written all of my code in one graphics with a bunch of nested ifs. Now I am trying to separate the two. Is there a way to call the gameGraphics method when the game is running, and then returning to the graphics method when you return to then menu?

here is my code:

// The "SpaceSpamEvolution" class.
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SpaceSpamEvolution extends Applet implements KeyListener, ActionListener
{

    Timer time;
    int screen;             // 1 = menu, 2 = game
    int select = 1;         // select from the menu 1 = play, 2 = change diffuculty, 3 = change color (maybe)
    int difficulty = 1; // 1 = easy, 2 = medium, 3 = difficult
    int gameDiff  ;      // gameDiff = difficulty
    // Place instance variables here
    
    public void init ()
    {
        
    
        // Place the body of the initialization method here
    } // init method
    
    
    
    public void paint (Graphics g)
    {
        g.setColor(Color.red);
        g.fillRect (10,10,10,10);
      // Place the body of the drawing method here
    } // paint method
    
    public void keyPressed (KeyEvent e){
        int key = e.getKeyCode ();
        if (key == KeyEvent.VK_ENTER && screen == 1){
            if (select == 1){
                gameDiff = difficulty;
                game (gameDiff);
            }
        }
        if (key == KeyEvent.VK_RIGHT && screen == 1){
            difficulty += 1;
            if (difficulty == 4){
                difficulty = 1;
            }
        }
        if (key == KeyEvent.VK_LEFT && screen == 1){
            difficulty -= 1;
            if (difficulty == 0){
                difficulty = 3;
            }
        }
    }
    public void keyReleased (KeyEvent e){}
    public void keyTyped (KeyEvent e){}
    
    
    
    
    public void game (int gameDiff){
        
        int delaytime;
        
        time = new Timer ((2000 - (500*gameDiff)), this);
        
    }
    public void gameGraphics (Graphics z){
        z.setColor (Color.blue);
        z.fillRect (50,50,50,50);
    }
    public void actionPerformed (ActionEvent e){}
} // SpaceSpamEvolution class

Thanks for any help.

what component you're trying to paint, if this Component starts with "J" f.e. JPanel, JLabel ...., then paint methods is wrong, replace that with paintComponent, if you want to overlap Compoents, than you have to set JCopmponent#setOpaque(false);

replace Applet with JApplet, because this Components died with unsuported Java 1.4

I am using graphics, not Jlabels etc. As you can see in line 29 and 69 I am drawing rectangles. This is what I am using the graphics for.

Do you know how to create an object (rectangle) in an array so that when a timer reaches a certain point a new rectangle will be drawn at a certain point? So far I have 2 rectangle and when they collide they reset. Could you also help me with when the new rectangles (one on each side) is printed, the program should check if they collide aswell as the previous rectangles. Would I have to program each rectangle collision detection separately or is it possible to just use one collision detection for all the rectangles. Here is my new code:

// The "SpaceSpamEvolution" class.
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SpaceSpamEvolution extends Applet implements KeyListener, ActionListener
{

    Timer time, tut;
    int screen = 1;             // 1 = menu, 2 = game
    int select = 1;         // select from the menu 1 = play, 2 = change diffuculty, 3 = change color
    int colSel = 1;         // the color selected from the menu (1 = blue,2 = red,3 = green,4 = yelow,5 = orange) Enermy always black
    Color playerCol;        // The players color
    int difficulty = 1; // 1 = easy, 2 = medium, 3 = difficult
    int gameDiff;        // gameDiff = difficulty
    int shaftx1 = 20, shaftx2 = 70, shafty1 = 50, shafty2 = shafty1;
    Font titleMenu = new Font ("Arial", 40, 40);
    int xpoints[] = {0, 25, 50};
    int ypoints[] = {300, 280, 300};
    int npoints = 3;
    int xpoints2[] = {550, 575, 600};
    int ypoints2[] = {300, 280, 300};
    Color sky = new Color (185, 211, 238);
    int tutx = 45;
    int tutenx = 550;
    int storage = 0;


    // Place instance variables here

    public void init ()
    {
        resize (600, 400);
        tut = new Timer (1000, this);

        addKeyListener (this);
        // Place the body of the initialization method here
    } // init method


    public void start ()
    {
        tut.start ();
    }


    public void paint (Graphics g)
    {
        g.setColor (sky);
        g.fillRect (0, 0, 600, 300);
        g.setColor (Color.black);
        g.setFont (titleMenu);
        g.drawString ("Play Game", 80, 65);
        g.drawString ("Difficulty: ", 80, 115);
        g.drawString ("Color Select: ", 80, 165);
        if (difficulty == 1)
        {
            g.setColor (Color.green);                       // changes color and prints difficulty
            g.drawString ("Easy", 250, 115);
        }
        else if (difficulty == 2)
        {
            g.setColor (Color.yellow);
            g.drawString ("Medium", 250, 115);
        }
        else if (difficulty == 3)
        {
            g.setColor (Color.red);
            g.drawString ("Hard", 250, 115);
        }
        if (colSel == 1)
        {
            playerCol = Color.blue;
        }
        else if (colSel == 2)
        {
            playerCol = Color.red;
        }
        else if (colSel == 3)
        {
            playerCol = new Color (0,100,0);
        }
        else if (colSel == 4)
        {
            playerCol = Color.yellow;
        }
        else if (colSel == 5)
        {
            playerCol = Color.orange;
        }
        
        g.setColor (Color.green);
        g.fillRect (0, 250, 600, 150);
        g.setColor (Color.gray);
        g.fillRect (0, 300, 50, 50);
        g.fillRect (550, 300, 50, 50);
        g.fillRect (0, 340, 550, 10);

        g.setColor (Color.black);                                       // animation at the bottom
        g.fillRect (tutenx, 335, 5,10);
        
        g.setColor (playerCol);
        g.fillRect (320, 140, 50, 30);

        g.fillRect (tutx, 335, 5, 10);           // tutorial rectangle      // animation code stops
        
        g.setColor (Color.red);
        g.fillPolygon (xpoints, ypoints, npoints);
        g.fillPolygon (xpoints2, ypoints2, npoints);
        g.fillRect (40, 330, 10, 20);
        g.fillRect (550, 330, 10, 20);
        g.setColor (Color.black);

        g.drawLine (0, 300, 50, 300);       // roof divider
        g.drawLine (550, 300, 600, 300);
        g.drawLine (shaftx1, shafty1, shaftx2, shafty2);
        g.drawLine (shaftx1 + 30, shafty1 + 20, shaftx2, shafty2);  // draws the arrow
        g.drawLine (shaftx1 + 30, shafty1 - 20, shaftx2, shafty2);
        
        // Place the body of the drawing method here
    } // paint method


    public void keyPressed (KeyEvent e)
    {
        int key = e.getKeyCode ();
        if (key == KeyEvent.VK_ENTER && screen == 1 && shafty1 == 50)
        { // checks the requirements to start the game
            if (select == 1)
            {
                gameDiff = difficulty;
                game (gameDiff, playerCol);
            }
        }
        if (key == KeyEvent.VK_RIGHT && screen == 1)
        { // changes the difficulty
            if (shafty1 == 100)
            {
                difficulty += 1;
                if (difficulty == 4)
                {
                    difficulty = 1;
                }
            }
            else if (shafty1 == 150)
            {
                if (colSel == 5)
                {
                    colSel = 1;
                }
                else
                {
                    colSel += 1;
                }
            }
            repaint ();
        }
        if (key == KeyEvent.VK_LEFT && screen == 1)
        {
            if (shafty1 == 100)
            {
                difficulty -= 1;
                if (difficulty == 0)
                {
                    difficulty = 3;
                }
            }
            else if (shafty1 == 150)
            {
                if (colSel == 1)
                {
                    colSel = 5;
                }
                else
                {
                    colSel -= 1;
                }
            }
            repaint ();
        }
        if (key == KeyEvent.VK_UP)
        { // changes the y location of the selection tool (arrow)
            if (shafty1 == 50)
            {
            }
            else
            {
                shafty1 -= 50;
                shafty2 = shafty1;
                repaint ();
            }
        }
        if (key == KeyEvent.VK_DOWN)
        {
            if (shafty1 == 150)
            {
            }
            else
            {
                shafty1 += 50;
                shafty2 = shafty1;
                repaint ();
            }
        }
    }


    public void keyReleased (KeyEvent e)
    {
    }


    public void keyTyped (KeyEvent e)
    {
    }


    /*
        ******************************************************************************************************************************************************
        ******************************************************************************************************************************************************
        *****  The Game **  The Game **  The Game **  The Game **  The Game **  The Game **  The Game **  The Game **  The Game **  The Game **  The Game ****
        ******************************************************************************************************************************************************
        ******************************************************************************************************************************************************


    */
    public void game (int gameDiff, Color playerCol)
    {

        int delaytime;

        time = new Timer ((2000 - (500 * gameDiff)), this);

    }


    public void gameGraphics (Graphics z)
    {
        z.setColor (Color.blue);
        z.fillRect (50, 50, 50, 50);
    }


    public void actionPerformed (ActionEvent e)
    {
        int unit = 0;
        if (unit == 10)
        {
            unit = 0;
            storage = 1;

        }
        if (screen == 1)
        {
            tutx += 3;
            tutenx -= 3;
            repaint ();
        }
        unit += 1;
        storage = 0;
        if (tutx + 5 >= tutenx){
            tutx = 50; tutenx = 550;
        }
    }
} // SpaceSpamEvolution class

Thanks

I do not think/mean it as an insult yor person, only to those trying to show what i spinning around, i knew how is hard to wrote something nice/excelent/bombastic

others gentlemens would you for this Atari ... under the black soil, please maybe I understood..., but never, not pait for AWT, use todays Swing

here is something, what you probably needed

very simple

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnimationJPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationJPanel panel = new AnimationJPanel();
                panel.setPreferredSize(new Dimension(400, 300));
                panel.animate();
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(panel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
    private int cx = 0; // circle's dimensions
    private int cy = 150;
    private int cw = 20;
    private int ch = 20;
    private int xinc = 1; // values to increment circle's position by
    private int yinc = 1;

    public AnimationJPanel() {
        setLayout(new BorderLayout());
        JLabel label = new JLabel("This is an AnimationJPanel");// JLabel for testing purposes
        label.setForeground(Color.RED);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        add(label);
        setBackground(Color.BLACK);// background to be black, circle red
        setForeground(Color.RED);
        setOpaque(true);
    }

    public void animate() {
        new Timer(15, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Rectangle oldCircle = new Rectangle(cx - 1, cy - 1, cw + 2, ch + 2);
                cx += xinc;
                cy += yinc;
                if (cx >= getWidth() - cw || cx <= 0) {
                    xinc *= -1;
                }
                if (cy >= getHeight() - ch || cy <= 0) {
                    yinc *= -1;
                }
                repaint(oldCircle);
                repaint(cx - 1, cy - 1, cw + 2, ch + 2);
            }
        }).start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(cx, cy, cw, ch);
    }
}

second level

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;

public class AnimationBackground {

    public AnimationBackground() {
        Random random = new Random();
        JFrame frame = new JFrame("Animation Background");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        final MyJPanel panel = new MyJPanel();
        panel.setBackground(Color.BLACK);
        for (int i = 0; i < 50; i++) {
            Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
            star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
            star.setxIncr(-3 + random.nextInt(7));
            star.setyIncr(-3 + random.nextInt(7));
            panel.add(star);
        }
        panel.setLayout(new GridLayout(10, 1));
        JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
        label.setForeground(Color.WHITE);
        panel.add(label);
        JPanel stopPanel = new JPanel();
        stopPanel.setOpaque(false);
        stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.stopAnimation();
            }
        }));
        panel.add(stopPanel);
        JPanel startPanel = new JPanel();
        startPanel.setOpaque(false);
        startPanel.add(new JButton(new AbstractAction("Start moving...") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.startAnimation();
            }
        }));
        panel.add(startPanel);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationBackground animationBackground = new AnimationBackground();
            }
        });
    }

    private class Star extends Polygon {

        private static final long serialVersionUID = 1L;
        private Point location = null;
        private Color color = Color.YELLOW;
        private int xIncr, yIncr;
        static final int WIDTH = 500, HEIGHT = 500;

        Star(Point location) {
            int x = location.x;
            int y = location.y;
            this.location = location;
            this.addPoint(x, y + 8);
            this.addPoint(x + 8, y + 8);
            this.addPoint(x + 11, y);
            this.addPoint(x + 14, y + 8);
            this.addPoint(x + 22, y + 8);
            this.addPoint(x + 17, y + 12);
            this.addPoint(x + 21, y + 20);
            this.addPoint(x + 11, y + 14);
            this.addPoint(x + 3, y + 20);
            this.addPoint(x + 6, y + 12);
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public void move() {
            if (location.x < 0 || location.x > WIDTH) {
                xIncr = -xIncr;
            }
            if (location.y < 0 || location.y > WIDTH) {
                yIncr = -yIncr;
            }
            translate(xIncr, yIncr);
            location.setLocation(location.x + xIncr, location.y + yIncr);
        }

        public void setxIncr(int xIncr) {
            this.xIncr = xIncr;
        }

        public void setyIncr(int yIncr) {
            this.yIncr = yIncr;
        }

        public Color getColor() {
            return color;
        }
    }

    private class MyJPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ArrayList<Star> stars = new ArrayList<Star>();
        private Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (Star star : stars) {
                    star.move();
                }
                repaint();
            }
        });

        public void stopAnimation() {
            if (timer.isRunning()) {
                timer.stop();
            }
        }

        public void startAnimation() {
            if (!timer.isRunning()) {
                timer.start();
            }
        }

        @Override
        public void addNotify() {
            super.addNotify();
            timer.start();
        }

        @Override
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        }

        MyJPanel() {
            this.setPreferredSize(new Dimension(512, 512));
        }

        public void add(Star star) {
            stars.add(star);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Star star : stars) {
                g.setColor(star.getColor());
                g.fillPolygon(star);
            }
        }
    }
}

painting lesson

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Reflector extends JPanel {

    private static final long serialVersionUID = 1L;
    private JComponent component;
    private Timer repaintTimer = new Timer(20, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            repaint();
        }
    });

    public Reflector(JComponent component) {
        this.component = component;
        setLayout(new GridLayout(2, 1));
        add(component);
        JPanel transparent = new JPanel();
        transparent.setOpaque(false);
        transparent.setPreferredSize(component.getPreferredSize());
        add(transparent);
    }

    @Override
    public void addNotify() {
        super.addNotify();
        repaintTimer.start();
    }

    @Override
    public void removeNotify() {
        super.removeNotify();
        repaintTimer.stop();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        g2.translate(0, getHeight());
        g2.scale(1, -1);
        component.paintAll(g2);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
        GradientPaint fadePaint = new GradientPaint(0, 0, getBackground(), 0,
                component.getHeight(), new Color(
                getBackground().getRGB() & 0xFFFFFF, true));
        g2.setPaint(fadePaint);
        g2.fillRect(0, 0, getWidth(), component.getHeight());
        g2.dispose();
    }

    private static void createGUI() {
        JFrame frame = new JFrame("Reflector");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(new JButton("Hello"));
        panel.add(new JTextField(20));
        Reflector reflector = new Reflector(panel);
        frame.add(reflector);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                createGUI();
            }
        });
    }
}

hmmmm

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.*;

public class BezierTest {

    private class Animator implements ActionListener {

        private double distance = 0;
        private boolean moveTo = true;
        private ArrayList<Point2D> points = new ArrayList<Point2D>();
        private double step = -1;
        private double steps;
        private Timer timer = new Timer(0, this);

        @Override
        public void actionPerformed(ActionEvent e) {
            step++;
            if (step <= steps) {
                double t = step / steps;
                Point2D newPoint = computeBezierPoint(new Point2D.Double(), t, curvePoints);
                marks[marks.length - 1].setFrame(newPoint.getX() - 5, newPoint.getY() - 5, 10, 10);
                points.add(newPoint);
                if (moveTo) {
                    path.moveTo(newPoint.getX(), newPoint.getY());
                    moveTo = false;
                } else {
                    path.lineTo(newPoint.getX(), newPoint.getY());
                }
                lines[3] = new Line2D.Double(computePointOnLine(lines[0], t), computePointOnLine(lines[1], t));
                lines[4] = new Line2D.Double(computePointOnLine(lines[1], t), computePointOnLine(lines[2], t));
                lines[5] = new Line2D.Double(computePointOnLine(lines[3], t), computePointOnLine(lines[4], t));
                // The maximum distance encountered between the results of two calculation methods.
                // newPoint from computeBezierPoint() the other via the lines method
                distance = Math.max(distance, newPoint.distance(computePointOnLine(lines[5], t)));
                demoComponent.repaint();
            } else {
                timer.stop();
                animationButton.setEnabled(true);
                if (distance > 0d) {
                    System.out.println("Maximum difference " + distance);
                }
            }
        }

        public void init() {
            timer.stop();
            animationButton.setEnabled(false);
            steps = sliderStep.getValue();
            step = -1;
            distance = 0;
            moveTo = true;
            path = new Path2D.Double();
            int sleepTime = (int) Math.round(1000d * sliderDuration.getValue() / steps);
            timer.setDelay(sleepTime);
            timer.setInitialDelay(0);
            timer.start();
        }

        private Point2D computeBezierPoint(Point2D rv, double t,
                Point2D... curve) {
            if (rv == null) {
                rv = new Point2D.Double();
            } else {
                rv.setLocation(0, 0);
            }
            int n = curve.length - 1;
            double oneMinusT = 1.0 - t;
            for (int index = 0; index < curve.length; index++) {
                double multiplier = index == 0 || index == n ? 1 : StrictMath.min(n - index, index) * n;
                multiplier *= StrictMath.pow(t, index) * StrictMath.pow(oneMinusT, n - index);
                rv.setLocation(rv.getX() + multiplier * curve[index].getX(), rv.getY() + multiplier * curve[index].getY());
            }
            return rv;
        }

        private Point2D computePointOnLine(Line2D line, double t) {
            return new Point2D.Double((line.getX2() - line.getX1()) * t + line.getX1(), (line.getY2() - line.getY1()) * t + line.getY1());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new BezierTest().createGUI();
            }
        });
    }
    private final JButton animationButton = new JButton(new AbstractAction("Start animation") {

        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            animator.init();
        }
    });
    private final Animator animator = new Animator();
    private Point2D[] curvePoints = new Point2D[]{new Point(10, 50), new Point(190, 10), new Point(190, 190), new Point(10, 150)};
    private JComponent demoComponent = new JComponent() {

        private static final long serialVersionUID = 1L;

        {
            setPreferredSize(new Dimension(400, 400));
            addComponentListener(new ComponentAdapter() {

                @Override
                public void componentResized(ComponentEvent e) {
                    int w = getWidth();
                    int h = getHeight();
                    recalculateAfterResize(w, h);
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            if (isVisible()) {
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, getWidth(), getHeight());
                super.paintComponent(g);
                paintBezier(g);
            }
        }
    };
    private Line2D[] lines = new Line2D[6];
    private final Ellipse2D[] marks;
    private Path2D path;
    private final JSlider sliderDuration = createSlider(1, 20, 2, "Duration in seconds", 9, 1);
    private final JSlider sliderStep = createSlider(8, 128, 64, "Animation steps", 16, 1);
    private Path2D totalCurve;

    {
        marks = new Ellipse2D[curvePoints.length + 1];
        for (int index = 0; index < marks.length; index++) {
            marks[index] = new Ellipse2D.Double();
        }
    }

    private void createGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(demoComponent, BorderLayout.CENTER);
        JToolBar toolBar = new JToolBar();
        toolBar.add(animationButton);
        toolBar.add(sliderStep);
        toolBar.add(sliderDuration);
        frame.add(toolBar, BorderLayout.PAGE_START);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JSlider createSlider(int min, int max, int value, String title, int major, int minor) {
        JSlider slider = new JSlider(min, max, value);
        slider.setBorder(BorderFactory.createTitledBorder(title));
        slider.setMajorTickSpacing(major);
        // slider.setMinorTickSpacing(minor);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);
        return slider;
    }

    private void paintBezier(Graphics g) {
        Path2D path1 = this.path;
        if (path1 != null) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.GREEN);
            for (Shape mark : marks) {
                g2.fill(mark);
            }
            g2.setStroke(new BasicStroke(2f));
            g2.setColor(Color.BLACK);
            for (Shape mark : marks) {
                g2.draw(mark);
            }
            g2.setStroke(new BasicStroke(0f));
            g2.draw(totalCurve);
            g2.setStroke(new BasicStroke(1f));
            g2.setColor(Color.RED);
            g2.draw(path1);
            g2.setStroke(new BasicStroke(.5f));
            g2.setColor(Color.BLACK);
            for (Line2D line : lines) {
                if (line != null) {
                    g2.draw(line);
                }
            }
        }
    }

    private void recalculateAfterResize(int w, int h) {
        curvePoints = new Point2D[]{new Point2D.Double(10, h / 4.0), new Point2D.Double(w - 10, 10), new Point2D.Double(w - 10, h - 10), new Point2D.Double(10, h - h / 4.0)};
        totalCurve = new Path2D.Double();
        totalCurve.moveTo(curvePoints[0].getX(), curvePoints[0].getY());
        totalCurve.curveTo(curvePoints[1].getX(), curvePoints[1].getY(), curvePoints[2].getX(), curvePoints[2].getY(), curvePoints[3].getX(), curvePoints[3].getY());
        for (int index = 0; index < curvePoints.length; index++) {
            marks[index].setFrame(curvePoints[index].getX() - 5, curvePoints[index].getY() - 5, 10, 10);
        }
        marks[marks.length - 1].setFrame(marks[0].getFrame());
        for (int index = 0; index < curvePoints.length - 1; index++) {
            lines[index] = new Line2D.Double(curvePoints[index], curvePoints[index + 1]);
        }
        lines[3] = null;
        lines[4] = null;
        lines[5] = null;
        animator.init();
    }
}

Edited 5 Years Ago by mKorbel: n/a

if you don't to surrender, then maybe once you get back to paint, It's so funny how to play with anything, for this still exist paint Method (sure for example)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalButtonUI;

public class TextAreaInButton {

    private JFrame frame = new JFrame("  sssssssss");
    private JButton tip1Null = new JButton(" test button ");

    public TextAreaInButton() {
        Border line, raisedbevel, loweredbevel, title, empty;
        line = BorderFactory.createLineBorder(Color.black);
        raisedbevel = BorderFactory.createRaisedBevelBorder();
        loweredbevel = BorderFactory.createLoweredBevelBorder();
        title = BorderFactory.createTitledBorder("");
        empty = BorderFactory.createEmptyBorder(1, 1, 1, 1);
        final Border compound;
        Color crl = (Color.blue);
        compound = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl));
        Color crl1 = (Color.red);
        final Border compound1;
        compound1 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl1));
        Color crl2 = (Color.black);
        final Border compound2;
        compound2 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl2));
        tip1Null.setFont(new Font("Serif", Font.BOLD, 14));
        tip1Null.setForeground(Color.darkGray);
        tip1Null.setPreferredSize(new Dimension(50, 30));
        tip1Null.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });
        tip1Null.setBorderPainted(true);
        tip1Null.setFocusPainted(false);
        tip1Null.setBorder(compound);
        tip1Null.setHorizontalTextPosition(SwingConstants.CENTER);
        tip1Null.setVerticalTextPosition(SwingConstants.BOTTOM);
        tip1Null.setUI(new ModifButtonUI());

        tip1Null.getModel().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                ButtonModel model = (ButtonModel) e.getSource();
                if (model.isRollover()) {
                    tip1Null.setBorder(compound1);
                } else {
                    tip1Null.setBorder(compound);
                }
                if (model.isPressed()) {
                    tip1Null.setBorder(compound2);
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(tip1Null, BorderLayout.CENTER);
        frame.setLocation(150, 150);
        frame.setPreferredSize(new Dimension(310, 50));
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TextAreaInButton taib = new TextAreaInButton();
            }
        });
    }
}

class OldRoundedBorderLine extends AbstractBorder {

    private final static int MARGIN = 5;
    private static final long serialVersionUID = 1L;
    private Color color;

    OldRoundedBorderLine(Color clr) {
        color = clr;
    }

    public void setColor(Color clr) {
        color = clr;
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(color);
        g.drawRoundRect(x, y, width, height, MARGIN, MARGIN);
    }

    @Override
    public Insets getBorderInsets(Component c) {
        return new Insets(MARGIN, MARGIN, MARGIN, MARGIN);
    }

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.left = MARGIN;
        insets.top = MARGIN;
        insets.right = MARGIN;
        insets.bottom = MARGIN;
        return insets;
    }
}

class ModifButtonUI extends MetalButtonUI {

    private static final ModifButtonUI buttonUI = new ModifButtonUI();

    ModifButtonUI() {
    }

    public static ComponentUI createUI(JComponent c) {
        return new ModifButtonUI();
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        final Color color1 = new Color(230, 255, 255, 0);
        final Color color2 = new Color(255, 230, 255, 64);
        final Color alphaColor = new Color(200, 200, 230, 64);
        final Color color3 = new Color(alphaColor.getRed(), alphaColor.getGreen(), alphaColor.getBlue(), 0);
        final Color color4 = new Color(alphaColor.getRed(), alphaColor.getGreen(), alphaColor.getBlue(), 64);
        super.paint(g, c);
        Graphics2D g2D = (Graphics2D) g;
        GradientPaint gradient1 = new GradientPaint(0.0F, (float) c.getHeight() / (float) 2, color1, 0.0F, 0.0F, color2);
        Rectangle rec1 = new Rectangle(0, 0, c.getWidth(), c.getHeight() / 2);
        g2D.setPaint(gradient1);
        g2D.fill(rec1);
        GradientPaint gradient2 = new GradientPaint(0.0F, (float) c.getHeight() / (float) 2, color3, 0.0F, c.getHeight(), color4);
        Rectangle rec2 = new Rectangle(0, c.getHeight() / 2, c.getWidth(), c.getHeight());
        g2D.setPaint(gradient2);
        g2D.fill(rec2);
    }

    @Override
    public void paintButtonPressed(Graphics g, AbstractButton b) {
        paintText(g, b, b.getBounds(), b.getText());
        g.setColor(Color.red.brighter());
        g.fillRect(0, 0, b.getSize().width, b.getSize().height);
    }

    public void paintBorder(Graphics g) {
    }

    @Override
    protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
    }
}

Edited 5 Years Ago by mKorbel: n/a

I am still new to java. Could you please comment the code to help me understand it? it would be much appreciated. thanks.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 * uses Key Binding pressed and released
 *
 * @author Pete
 *
 */
public class MoveIcon extends JPanel {

    private static final long serialVersionUID = 1L;

    enum Direction {

        UP(KeyEvent.VK_UP, 0, -1), DOWN(KeyEvent.VK_DOWN, 0, 1),
        LEFT(KeyEvent.VK_LEFT, -1, 0), RIGHT(KeyEvent.VK_RIGHT, 1, 0);
        private int keyCode;
        private int xDirection;
        private int yDirection;

        private Direction(int keyCode, int xDirection, int yDirection) {
            this.keyCode = keyCode;
            this.xDirection = xDirection;
            this.yDirection = yDirection;
        }

        public int getKeyCode() {
            return keyCode;
        }

        public int getXDirection() {
            return xDirection;
        }

        public int getYDirection() {
            return yDirection;
        }
    }
    private static final String IMAGE_PATH = "http://duke.kenai.com/misc/Bullfight.jpg";
    private static final String IMAGE_PATH_PLAYER = "http://duke.kenai.com/iconSized/duke4.gif";
    public static final int STEP = 3;
    private static final int TIMER_DELAY = STEP * 8;
    private BufferedImage bkgrndImage = null;
    private BufferedImage playerImage = null;
    private Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
    private int playerX = 0;
    private int playerY = 0;

    public MoveIcon() {
        try {
            URL bkgrdImageURL = new URL(IMAGE_PATH);
            URL playerImageURL = new URL(IMAGE_PATH_PLAYER);
            bkgrndImage = ImageIO.read(bkgrdImageURL);
            playerImage = ImageIO.read(playerImageURL);
            setPreferredSize(new Dimension(bkgrndImage.getWidth(), bkgrndImage.getHeight()));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Direction direction : Direction.values()) {
            directionMap.put(direction, false);
        }
        setKeyBindings();
        Timer timer = new Timer(TIMER_DELAY, new TimerListener());
        timer.start();
    }

    private void setKeyBindings() {
        InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actMap = getActionMap();
        for (final Direction direction : Direction.values()) {
            KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
            KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
            inMap.put(pressed, direction.toString() + "pressed");
            inMap.put(released, direction.toString() + "released");
            actMap.put(direction.toString() + "pressed", new AbstractAction() {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    directionMap.put(direction, true);
                }
            });
            actMap.put(direction.toString() + "released", new AbstractAction() {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    directionMap.put(direction, false);
                }
            });
        }

    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (bkgrndImage != null) {
            g.drawImage(bkgrndImage, 0, 0, null);
        }
        if (playerImage != null) {
            g.drawImage(playerImage, playerX, playerY, null);
        }
    }

    private class TimerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            boolean moved = false;
            for (Direction direction : Direction.values()) {
                if (directionMap.get(direction)) {
                    playerX += STEP * direction.getXDirection();
                    playerY += STEP * direction.getYDirection();
                    moved = true;
                }
            }
            if (moved) {
                int x = playerX - 2 * STEP;
                int y = playerY - 2 * STEP;
                int w = playerImage.getWidth() + 4 * STEP;
                int h = playerImage.getHeight() + 4 * STEP;
                MoveIcon.this.repaint(x, y, w, h); // !! repaint just the player
            }
        }
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("MoveIcon");
        frame.getContentPane().add(new MoveIcon());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Ok I have started working on applications but I cannot get the action for the button working. I may be doing this completely wrong so bare with me. here is the code:

//import javax.swing.SwingUtilities;
//import javax.swing.JFrame;

//import javax.swing.JPanel;
import javax.swing.*;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;


public class BasicApplication
{
    
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            public void run ()
            {
          
        
                createAndShowGUI ();         // creates new method

            }
        }
        );
    }


    private static void createAndShowGUI ()
    {
        System.out.println ("Created GUI on EDT? " +
                SwingUtilities.isEventDispatchThread ());
        JFrame f = new JFrame ("Swing Paint Demo");                     // names window
        f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);             // sets close type
        
        f.add (new MyPanel ());                              // adds a JPannel
        f.setSize (250,200);   
        f.pack ();                                          // calls getPreferredSize method                                
         
                  
        f.setVisible (true);                             // sets all visible


    }
}





class MyPanel extends JPanel implements ActionListener
{
    JLabel paste;
    String pasted;
    public MyPanel ()
    {
        
        setBorder (BorderFactory.createLineBorder (Color.black));
        JButton b1 = new JButton ("Click me to paste");
        JTextField field = new JTextField (20);
        JLabel title = new JLabel ("Type text then click the button: ");
        pasted = field.getText();
        paste = new JLabel ("");
        add (title);
        //b1.setPreferredSize(new Dimension(25, 25));  
        add (b1);      
        add (field);
        add (paste);
        b1.setActionCommand ("true");
        b1.addActionListener (this);
    }

    public void ActionPerformed (ActionEvent e){
        if (e.getActionCommand ().equals  ("true")){
            paste.setText (pasted);
        }
        
    }
    
    public Dimension getPreferredSize ()
    {
        return new Dimension (250, 200);
    }


    public void paintComponent (Graphics g)
    {
        super.paintComponent (g);

        // Draw Text
        //g.drawString ("This is my custom Panel!", 10, 20);              // prints //text
        //g.setColor (Color.red);                                    // sets color
        //g.fillOval (115,100,10,10);                                // prints oval
       // g.setColor (Color.black);
    }
}

Thanks for any help. This code is supposed to take the text the user inputed and then paste in underneath the JTextField.

I found the problem with the ActionListener. Change the ActionPerformed (ActionEvent e) to actionPerformed (ActionEvent e), but now it is not pasting what the user wrote.

This article has been dead for over six months. Start a new discussion instead.