Question

MasterMind in Java

Activity

MasterMind project

Create a new Java Application project named MasterMind

allowing Netbeans IDE to create the main class called MasterMind.java

MasterMind class

Method main() should:

  1. Call static method System.out.println() and result in displaying “Welcome to MasterMind!”
  2. Call static method JOptionPane.showMessageDialog(arg1, arg2) and result in displaying a message dialog displaying “Let’s Play MasterMind!”
  3. Instantiate an instance of class Game()

constants

Create package

Constants class

Create class Constants

Create constants by declaring them as “public static final”:

  1. public static final ArrayList codeColors = new ArrayList(Arrays.asList(Color.BLUE, Color.BLACK, Color.ORANGE, Color.WHITE, Color.YELLOW, Color.RED, Color.GREEN, Color.PINK));
  2. ArrayList responseColors = new ArrayList(Arrays.asList(Color.RED, Color.WHITE));
  3. int MAX_ATTEMPTS = 10;
  4. int MAX_PEGS = 4;
  5. int COLORS = 8;

core package

Create package core

Codebreaker class

Create class Codebreaker so it implements interface ICodebreaker

  1. Member variables
    1. ArrayList codebreakerAttempt
  2. Getter/setter for member variables
  3. Custom constructor
    1. Empty parameter list
    2. Instantiates the member variable
  4. Implements ICodebreaker interface method
    1. public void checkCode(ArrayList attempt)

Codemaker class

Create class Codemaker so it implements interface ICodemaker

  1. Member variables
    1. Set secretCode
    2. ArrayList codemakerResponse
  2. Getter/setter for member variables
  3. Custom constructor
    1. Empty parameter list
    2. Instantiates the member variables
      1. Member variable secretCode should be instantiated as an instance of class HashSet()
      2. Member variable codemakerResponse should be instantiated as an instance of class ArrayList()
    3. Calls method generateSecretCode()
  4. Implements ICodemaker interface methods
    1. public void generateSecretCode()
    2. public void checkAttemptedCode()
  5. Method generateSecretCode()
    1. Instantiate and instance of Java API class Random
    2. Loop until four of the eight colors have been randomly selected to be the secret code with no duplicates (hint: member variable secretCode is of type Set which automatically does not allow for duplicates)
      1. Use the method .nextInt() in class Random to select an index into the Constants.codeColors ArrayList, pass the ArrayList as an argument to the method call
      2. Create an instance of Java API class Color and set it equal to the color stored at the index of the Constants.codeColors ArrayList by calling the get() method in class ArrayList passing the int from step i. above as an argument
      3. Add the selected color to the Set member variable by calling method .add in class Set passing the Color object from step ii. above as and argument
    3. Use an enhanced for loop to output the generated secret code

Game class

Create class Game so it implements interface IGame

  1. Member variables
    1. int attempt
    2. Codebreaker codebreaker
    3. Codemaker codemaker
  2. Getter/setter for member variables
  3. Custom constructor
    1. Empty parameter list
    2. Instantiates the member variables
  4. Implements IGame interface methods
    1. public void play()

ICodebreaker interface

Create interface ICodebreaker

  1. Add method signatures
    1. public void checkCode(ArrayList attempt)

ICodemaker interface

Create interface ICodemaker

  1. Add method signatures
    1. public void generateSecretCode()
    2. public void checkAttemptedCode()

IGame interface

Create interface IGame

  1. Add method signatures
    1. public void play()

userInterface package

Create package userInterface

MasterMindUi class

Create class MasterMindUi

MasterMind application

Perform the following test cases

Test Cases

Action

Expected outcome

Test Case 1

Project view

Completed project view should look like figure 1

Test case 2

Run application

The console window should look like figure 2                                                                      

Test case 3

Run application

The JOptionPane.showMessageDialog() method call should look like figure 3

Test case 4

Run application

The console window should be similar to figure 4

Java does NOT automatically translate its Color objects to a String value, rather it prints the RGB code of the color.      

MasterMind Source Packages constants Constants.java core Codebreaker.java Codemaker.java Game.java ICodebreaker.java ICodemak

Figure 1 Project View

Output MasterMind (run) x run: Welcome to MasterMind!

Figure 2 Output in console window

Message Lets Play MasterMind! OK X

Figure 3 Display from JOptionPane.showMessageDialog() method

Welcome to MasterMind! generated the secret code! java.awt.Color [r-255, g=175, b-175 java.awt.Color [r-0, g 0,b-255 java.awt

Figure 4 Secret Code

MasterMind Source Packages constants Constants.java core Codebreaker.java Codemaker.java Game.java ICodebreaker.java ICodemaker.java IGame.java mastermind MasterMind.java userinterface MasterMindUi.java alfalfal ..I
Output MasterMind (run) x run: Welcome to MasterMind!
Message Let's Play MasterMind! OK X
Welcome to MasterMind! generated the secret code! java.awt.Color [r-255, g=175, b-175 java.awt.Color [r-0, g 0,b-255 java.awt.Color [r-255, g-200, b-0 java.awt.Color [r-255, g-0, b-0 BUILD SUCCESSFUL (total time: 2 seconds)
0 0
Add a comment Improve this question Transcribed image text
Answer #1


Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)

import javax.swing.JOptionPane;


public class MasterMind {


    public static void main(String[] args) {
        System.out.println("Welcome to MasterMind!");
        JOptionPane.showMessageDialog(null, "Let's Play MasterMind!");
        System.out.println("generated the secret code!");
        Game g = new Game();

        MasterMindUi master = new MasterMindUi(g);

    }

}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;

public class MasterMindUi {
    Game game;
    CodebreakerUi codebreakerUi;
    CodemakerUi codemakerUi;
    JFrame frame;
    JMenuBar menuBar;
    JMenu gameMenu;
    JMenu helpMenu;
    JMenuItem newGameMenuItem;
    JMenuItem exitMenuItem;
    JMenuItem aboutMenuItem;
    JMenuItem rulesMenuItem;

    public MasterMindUi(Game game) {

        codebreakerUi = new CodebreakerUi(game.getCodebreaker());
        codemakerUi = new CodemakerUi(game.getCodemaker());

        initComponents();

    }
    public void initComponents(){
        frame = new JFrame();
        gameMenu = new JMenu("Game");
        helpMenu = new JMenu("Help");
        newGameMenuItem = new JMenuItem("New Game");
        exitMenuItem = new JMenuItem("Exit");
        aboutMenuItem = new JMenuItem("About");
        rulesMenuItem = new JMenuItem("Rules");
        Dimension preferSize = new Dimension(800, 700);
        frame.setPreferredSize(preferSize);
        frame.setMinimumSize(preferSize);
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        menuBar = new JMenuBar();
        menuBar.add(gameMenu);
        gameMenu.add(newGameMenuItem);
        gameMenu.add(exitMenuItem);
        menuBar.add(helpMenu);
        helpMenu.add(aboutMenuItem);
        helpMenu.add(rulesMenuItem);
        frame.setJMenuBar(menuBar);

        ExitAction exitact = new ExitAction();
        AboutAction aboutact = new AboutAction();
        RuleAction ruleact = new RuleAction();

        exitMenuItem.addActionListener(exitact);
        aboutMenuItem.addActionListener(aboutact);
        rulesMenuItem.addActionListener(ruleact);

        frame.add(codebreakerUi.getCodebreakerAttempt(), BorderLayout.LINE_START);
        frame.add(codebreakerUi.getCodebreakerColors(), BorderLayout.PAGE_END);
        frame.add(codemakerUi.getCodemakerResponse(), BorderLayout.LINE_END);
        frame.add(codemakerUi.getSecretCode(), BorderLayout.PAGE_START);

        frame.setVisible(true);
    }

    public class ExitAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {

            if(JOptionPane.showConfirmDialog(null, "Confirm to exit MasterMind?", "Exit?",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
                System.exit(0);
            }
        }
    }

    public class AboutAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {

            JOptionPane.showMessageDialog(null, "MasterMind");

        }
    }

    public class RuleAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {

            JOptionPane.showMessageDialog(null, "Step 1: The codemaker selects a four color secret code, in any order, no duplicate colors.\n\nStep 2: The codebreaker places a guess in the bottom row, no duplicate colors.\n\nStep 3: The codemaker gives feedback next to each guess row with four pegs\n~ Each red peg means that one of the guessed colors is correct, and is in the right location.\n~ Each white pegs means that one of the guessed colors is correct, but is in the wrong location.\n\nStep 4: Repeat with the next row, unless the secret code was guessed on the first turn.\n\nStep 5: Continue until the secret code is guessed or there are no more guesses left, there are 10 attempts.");

        }
    }
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.awt.Color;
import java.util.Scanner;
public class Codebreaker implements ICodebreaker {
    public static ArrayList<Color> codebreakerAttempt;
    public ArrayList getCodebreakerAttempt(){
        return codebreakerAttempt;
    }
    public void setCodebreakerAttempt(ArrayList codebreakerAttempt){
        this.codebreakerAttempt = codebreakerAttempt;
    }
    public Codebreaker(){
        codebreakerAttempt = new ArrayList();
    }

    public void checkCode(ArrayList<Color> attempt){

    }
    private void consoleAttempt(){
        codebreakerAttempt.clear();
        Scanner scan = new Scanner(System.in);
        Color c = null;

        System.out.println("\nEnter your colors in left to right order\n" + "Use BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
        for(int i = 0; i < 4;)
        {
            String str = scan.next();
            String strUp = str.toUpperCase();


            if(strUp.equals("BLUE"))
            {
                c = Color.BLUE;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("BLACK"))
            {
                c = Color.BLACK;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("ORANGE"))
            {
                c = Color.ORANGE;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("WHITE"))
            {
                c = Color.WHITE;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("YELLOW"))
            {
                c = Color.YELLOW;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("RED"))
            {
                c = Color.RED;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("GREEN"))
            {
                c = Color.GREEN;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else if(strUp.equals("PINK"))
            {
                c = Color.PINK;
                if(codebreakerAttempt.contains(c))
                {
                    System.out.println("You have already entered this color!");
                }
                else
                {
                    System.out.println("You entered " + strUp);
                    codebreakerAttempt.add(c);
                    i++;
                }
            }
            else
            {
                System.out.println("You have entered an invalid color");
            }

            if(codebreakerAttempt.size() < Constants.MAX_PEGS)
            {
                System.out.println("Next color");
            }
        }
        System.out.println("Codebreaker's Attempt:");
        for(Color col : codebreakerAttempt)
        {
            System.out.println(col);
        }


    }

    public void removeAll()
    {

        codebreakerAttempt.clear();

    }


}


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

public class CodebreakerUi {

    JPanel codebreakerAttempt;
    JPanel codebreakerColors;
    Codebreaker codebreaker;
    RoundButton[] buttons;
    RoundButton[][] attempts;
    Color colorSelected;


    public JPanel getCodebreakerAttempt(){
        return codebreakerAttempt;
    }

    public JPanel getCodebreakerColors(){
        return codebreakerColors;
    }

    public CodebreakerUi(Codebreaker br) {
        codebreaker = br;

        initComponents();

    }

    public void initComponents(){

        codebreakerAttempt = new JPanel();
        codebreakerColors = new JPanel();
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
        GridLayout grid = new GridLayout(10, 4);


        codebreakerAttempt.setMinimumSize(new Dimension(460, 550));
        codebreakerAttempt.setPreferredSize(new Dimension(460, 550));
        codebreakerAttempt.setBorder(BorderFactory.createTitledBorder("Codebreaker Attempt"));
        codebreakerAttempt.setLayout(grid);
        codebreakerColors.setMinimumSize(new Dimension(800, 50));
        codebreakerColors.setPreferredSize(new Dimension(800, 50));
        codebreakerColors.setBorder(BorderFactory.createTitledBorder("Codebreaker Colors"));
        codebreakerColors.setLayout(flow);
        buttons = new RoundButton[8];
        attempts = new RoundButton[10][4];
        for(int i = 0; i < buttons.length; i++)
        {
            buttons[i] = new RoundButton();
            buttons[i].setMinimumSize(new Dimension(50, 50));
            buttons[i].setPreferredSize(new Dimension(25, 25));
            Color col = Constants.codeColors.get(i);
            buttons[i].setBackground(col);
            buttons[i].putClientProperty("color", col);
            buttons[i].setToolTipText(col.toString());
            SelectButton select = new SelectButton();
            buttons[i].addActionListener(select);
            codebreakerColors.add(buttons[i]);
        }
        for(int n = 0; n < attempts.length; n++)
        {
            for(int j = 0; j < attempts[n].length; j++)
            {
                attempts[n][j] = new RoundButton();
                attempts[n][j].putClientProperty("row", attempts[n]);
                if(n != (attempts.length-1))
                {
                    attempts[n][j].setEnabled(false);
                }
                else
                {
                    attempts[n][j].setEnabled(true);
                }
                codebreakerAttempt.add(attempts[n][j]);
            }

        }

    }

    public class SelectButton implements ActionListener{

        public void actionPerformed(ActionEvent e)
        {
            RoundButton instbutton = new RoundButton();
            Object ob = e.getSource();
            instbutton = (RoundButton)ob;
        }


    }

}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.awt.Color;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Codemaker implements ICodemaker {
    static Set<Color> secretCode;
    static ArrayList<Color> codemakerResponse;
    static ArrayList<Color> secretlist;
    public Set getSecretCode(){
        return secretCode;
    }
    public ArrayList getCodemakerResponse(){
        return codemakerResponse;
    }
    public void setSecretCode(Set secretCode){
        this.secretCode = secretCode;
    }
    public void setCodemakerResponse(ArrayList codemakerResponse){
        this.codemakerResponse = codemakerResponse;
    }
    public Codemaker(){
        secretCode = new HashSet();
        codemakerResponse = new ArrayList();
        generateSecretCode();
    }
    public ArrayList getsecretlist(){
        return secretlist;
    }
    public void checkAttemptedCode(ArrayList<Color> colorlist)
    {
        int red = 0, white = 0, n = 0;
        Set<Color> pegs = new HashSet();
        secretlist = new ArrayList<Color>(secretCode);

        System.out.println("Codemaker is checking codebreaker's attempt");
        if(secretlist.equals(Codebreaker.codebreakerAttempt))
        {
            System.out.println("Your guessed it!!!");

            red = 4;
            white = 0;
        }
        else
        {
            for(int i = 0; i < Constants.MAX_PEGS; i++)
            {
                if(secretlist.get(i) == Codebreaker.codebreakerAttempt.get(i))
                {
                    System.out.println("Found correct color in correct position!");
                    red++;
                    pegs.add(Codebreaker.codebreakerAttempt.get(i));
                }
            }
            for(Color color : Codebreaker.codebreakerAttempt)
            {
                if(secretlist.get(n) != color && secretlist.contains(color) && !pegs.contains(color))
                {
                    System.out.println("Found correct color in wrong position");
                    white++;
                    pegs.add(color);
                }

                n++;
            }
        }

        System.out.println("Red pegs: " + red + " White pegs: " + white);
        for(int i = 0; i < red; i++)
        {
            codemakerResponse.add(Color.RED);
        }
        for(int i = 0; i < white; i++)
        {
            codemakerResponse.add(Color.WHITE);
        }
        System.out.println("Codemaker's Response:");
        for(Color colors : codemakerResponse)
        {
            System.out.println(colors);
        }
        codemakerResponse.clear();
    }
    public void generateSecretCode(){
        Random rand = new Random();
        Color col;
        int index;
        for(int i = 0; i < 4; )
        {
            index = 0 + rand.nextInt(7);
            col = Constants.codeColors.get(index);
            if(secretCode.add(col)){
                i++;
            }

        }
        for(Color c : secretCode){

            System.out.println(c);
        }

    }

}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class CodemakerUi {

    JPanel codemakerResponse;
    JPanel secretCode;
    Codemaker codemaker;
    JLabel[] secretLabels;
    JLabel[][] responseLabels;
    ImageIcon question;


    public JPanel getCodemakerResponse(){
        return codemakerResponse;
    }

    public JPanel getSecretCode(){
        return secretCode;
    }

    public CodemakerUi(Codemaker make) {

        codemaker = make;

        initComponents();

    }

    private ImageIcon imageResize(ImageIcon icon)
    {
        Image image = icon.getImage();
        Image newImage = image.getScaledInstance(30, 30, java.awt.Image.SCALE_SMOOTH);
        icon = new ImageIcon(newImage);
        return icon;
    }


    public void initComponents(){

        codemakerResponse = new JPanel();
        secretCode = new JPanel();

        FlowLayout flow = new FlowLayout();
        GridLayout grid = new GridLayout(10, 4);


        codemakerResponse.setMinimumSize(new Dimension(310, 550));
        codemakerResponse.setPreferredSize(new Dimension(310, 550));
        codemakerResponse.setBorder(BorderFactory.createTitledBorder("Codemaker Response"));
        codemakerResponse.setLayout(grid);
        secretCode.setMinimumSize(new Dimension(800, 50));
        secretCode.setPreferredSize(new Dimension(800, 50));
        secretCode.setBorder(BorderFactory.createTitledBorder("Secret Code"));
        secretCode.setLayout(flow);
        secretLabels = new JLabel[4];
        responseLabels = new JLabel[10][4];
        question = new ImageIcon(getClass().getResource("/Users/swapnil/IdeaProjects/MasterMindProgram/src/question.jpg"));
        for(int i = 0; i < secretLabels.length; i++)
        {
            secretLabels[i] = new JLabel();
            ImageIcon image = new ImageIcon();
            image = imageResize(question);
            secretLabels[i].setIcon(image);
            secretCode.add(secretLabels[i]);
        }
        JButton button = new JButton("Check");

        secretCode.add(button);
        for(int n = 0; n < responseLabels.length; n++)
        {
            for(int j = 0; j < responseLabels[n].length; j++)
            {
                responseLabels[n][j] = new JLabel();
                responseLabels[n][j].setBorder(BorderFactory.createLineBorder(Color.black));
                codemakerResponse.add(responseLabels[n][j]);
            }
        }

    }

}


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.util.Arrays;
import java.util.ArrayList;
import java.awt.Color;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;


public class Constants {
    public static final ArrayList<Color> codeColors = new ArrayList<Color>(Arrays.asList(Color.BLUE, Color.BLACK, Color.ORANGE, Color.WHITE, Color.YELLOW, Color.RED, Color.GREEN, Color.PINK));
    public static final ArrayList<Color> responseColors = new ArrayList<Color>(Arrays.asList(Color.RED, Color.WHITE));
    public static final int MAX_ATTEMPTS = 10;
    public static final int MAX_PEGS = 4;
    public static final int COLORS = 8;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.util.ArrayList;
public class Game implements IGame {
    int attempt;
    Codebreaker codebreaker;
    Codemaker codemaker;
    public int getAttempt(){
        return attempt;
    }
    public Codebreaker getCodebreaker(){
        return codebreaker;
    }
    public Codemaker getCodemaker(){
        return codemaker;
    }
    public void setAttempt(int attempt){
        this.attempt = attempt;
    }
    public void setCodebreaker(Codebreaker codebreaker){
        this.codebreaker = codebreaker;
    }
    public void setCodemaker(Codemaker codemaker){
        this.codemaker = codemaker;
    }
    public Game(){
        codebreaker = new Codebreaker();
        codemaker = new Codemaker();
        play();
    }
    public void play(){
        for(int i = 0; (i < Constants.MAX_ATTEMPTS) && !(Codebreaker.codebreakerAttempt.equals(Codemaker.secretlist)); i++)
        {
            ArrayList<Color> list = codebreaker.getCodebreakerAttempt();
            codemaker.checkAttemptedCode(list);
            ArrayList<Color> newlist = codemaker.getCodemakerResponse();

            System.out.println("Codemaker's Response:");

            for(Color c : newlist)
            {
                System.out.println(c);
            }
        }
    }
}


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.util.ArrayList;


public interface ICodebreaker {
    public void checkCode(ArrayList<Color> attempt);
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.util.ArrayList;


public interface ICodemaker {
    public void generateSecretCode();
    public void checkAttemptedCode(ArrayList<Color> colorlist);
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public interface IGame {
    public void play();
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Dimension;
import java.awt.geom.Ellipse2D;

public class RoundButton extends RoundedCornerButton
{
    protected RoundButton()
    {
        super();
    }

    @Override
    public Dimension getPreferredSize()
    {
        Dimension d = super.getPreferredSize();
        int s = Math.max(d.width, d.height);
        d.setSize(s, s);
        return d;
    }

    @Override
    protected void initShape()
    {
        if (!getBounds().equals(base))
        {
            base = getBounds();
            shape = new Ellipse2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
            border = new Ellipse2D.Double(FOCUS_STROKE, FOCUS_STROKE,
                    getWidth() - 1 - FOCUS_STROKE * 2,
                    getHeight() - 1 - FOCUS_STROKE * 2);
        }
    }
}


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JButton;

public class RoundedCornerButton extends JButton
{
    private static final double ARC_WIDTH = 16d;
    private static final double ARC_HEIGHT = 16d;
    protected static final int FOCUS_STROKE = 2;
    protected final Color fc = new Color(100, 150, 255, 200);
    protected final Color ac = new Color(230, 230, 230);
    protected final Color rc = Color.ORANGE;
    protected Shape shape;
    protected Shape border;
    protected Shape base;

    protected RoundedCornerButton()
    {
        super();
    }

    @Override
    public void updateUI()
    {
        super.updateUI();
        setContentAreaFilled(false);
        setFocusPainted(false);
        setBackground(new Color(250, 250, 250));
        initShape();
    }

    protected void initShape()
    {
        if (!getBounds().equals(base))
        {
            base = getBounds();
            shape = new RoundRectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1, ARC_WIDTH, ARC_HEIGHT);
            border = new RoundRectangle2D.Double(FOCUS_STROKE, FOCUS_STROKE,
                    getWidth() - 1 - FOCUS_STROKE * 2,
                    getHeight() - 1 - FOCUS_STROKE * 2,
                    ARC_WIDTH, ARC_HEIGHT);
        }
    }

    private void paintFocusAndRollover(Graphics2D g2, Color color)
    {
        g2.setPaint(new GradientPaint(0, 0, color, getWidth() - 1, getHeight() - 1, color.brighter(), true));
        g2.fill(shape);
        g2.setPaint(getBackground());
        g2.fill(border);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        initShape();
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (getModel().isArmed())
        {
            g2.setPaint(ac);
            g2.fill(shape);
        }
        else if (isRolloverEnabled() && getModel().isRollover())
        {
            paintFocusAndRollover(g2, rc);
        }
        else if (hasFocus())
        {
            paintFocusAndRollover(g2, fc);
        }
        else
        {
            g2.setPaint(getBackground());
            g2.fill(shape);
        }

        g2.dispose();
//        super.paintComponent(g);
    }

    @Override
    protected void paintBorder(Graphics g)
    {
        initShape();
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(getForeground());
        g2.draw(shape);
        g2.dispose();
    }

    @Override
    public boolean contains(int x, int y)
    {
        initShape();
        return shape != null && shape.contains(x, y);
    }
}



MasterMindProgram [~/ldeaProjects/MasterMind Program]- .../src/MasterMind.java [MasterMind Program Q MasterMindProgram sre Ma

Add a comment
Know the answer?
Add Answer to:
MasterMind in Java Activity MasterMind project Create a new Java Application project named MasterMind allowing Netbeans...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Project In Brief... For this Java project, you will create a Java program for a...

    Java Project In Brief... For this Java project, you will create a Java program for a school. The purpose is to create a report containing one or more classrooms. For each classroom, the report will contain: I need a code that works, runs and the packages are working as well The room number of the classroom. The teacher and the subject assigned to the classroom. A list of students assigned to the classroom including their student id and final grade....

  • Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

    Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method: public abstract Product get(String productCode); Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this: IProductDB db...

  • signature 1. Create a new NetBeans Java project. The name of the project has to be...

    signature 1. Create a new NetBeans Java project. The name of the project has to be the first part of the name you write on the test sheet. The name of the package has to be testo You can chose a name for the Main class. (2p) 2. Create a new class named Address in the test Two package. This class has the following attributes: city: String-the name of the city zip: int - the ZIP code of the city...

  • q2: Write a public class named MythMouseListener that implements the Mouselistener interface. This class will have...

    q2: Write a public class named MythMouseListener that implements the Mouselistener interface. This class will have a public constructor that takes a JTextArea and a JLabel as parameters and stores these in instance variables. Override the mouseEntered method to . display the text from the JTextArea on the JLabel in all upper case letters. Then, override the mouseReleased method to display the text from the JTextArea on the JLabel in all lower case letters. The other three methods from the...

  • // Client application class and service class Create a NetBeans project named StudentClient following the instructions...

    // Client application class and service class Create a NetBeans project named StudentClient following the instructions provided in the Starting a NetBeans Project instructions in the Programming Exercises/Projects Menu on Blackboard. Add a class named Student to the StudentClient project following the instructions provided in the Starting a NetBeans Project instructions in the Programming Exercises/Projects Menu on Blackboard. After you have created your NetBeans Project your application class StudentC lient should contain the following executable code: package studentclient; public class...

  • help please Perform the following steps: a) Using NetBeans, Create a New Java Application Project with...

    help please Perform the following steps: a) Using NetBeans, Create a New Java Application Project with Project Name BasePlusCommission Employee Test with Create Main Class check box selected. Create comments to form a descriptive header that has the course name, your name, the assignment title, and a pledge that you have neither received nor provided help to any person. Assignments submitted without this pledge will not be graded. When you have completed the steps (b) and (c) below, you will...

  • Project 9-2: Account Balance Calculator Create an application that calculates and displays the starting and ending...

    Project 9-2: Account Balance Calculator Create an application that calculates and displays the starting and ending monthly balances for a checking account and a savings account. --->Console Welcome to the Account application Starting Balances Checking: $1,000.00 Savings:  $1,000.00 Enter the transactions for the month Withdrawal or deposit? (w/d): w Checking or savings? (c/s): c Amount?: 500 Continue? (y/n): y Withdrawal or deposit? (w/d): d Checking or savings? (c/s): s Amount?: 200 Continue? (y/n): n Monthly Payments and Fees Checking fee:              $1.00 Savings...

  • (JAVA NetBeans) Write programs in java Example 10.21-24 //Animal.java /** Animal class * Anderson. Franceschi */...

    (JAVA NetBeans) Write programs in java Example 10.21-24 //Animal.java /** Animal class * Anderson. Franceschi */ import java.awt.Graphics; public abstract class Animal { private int x; // x position private int y; // y position private String ID; // animal ID /** default constructor * Sets ID to empty String */ public Animal( ) { ID = ""; } /** Constructor * @param rID Animal ID * @param rX x position * @param rY y position */ public Animal( String...

  • ISu a The paradox d I ata fields (or mputers. Program 3 Assume the existence of a class called Vo...

    ISu a The paradox d I ata fields (or mputers. Program 3 Assume the existence of a class called Voter which defines two instance variables: Add 10 user to the ArrayList. private String name; rivate char party: 'D'for Democrat or 'R' for Republican Assume that this class implements these two methods: public char getParty() public String tostring) // name and party affiliation Now assume you're in the main method in another class called VoterDriver. Write a Java statement that instantiates...

  • Define an interface named Shape with a single method named area that calculates the area of...

    Define an interface named Shape with a single method named area that calculates the area of the geometric shape:        public double area(); Next, define a class named Circle that implements Shape. The Circle class should have an instance variable for the radius, a constructor that sets the radius, an accessor and a mutator method for the radius, and an implementation of the area method. Define another class named Rectangle that implements Shape. The Rectangle class should have instance variables...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT