Question

Activity: Build a simple GUI application using a JCombo box and images. Use of a GUI Builder is ...

Activity:

  1. Build a simple GUI application using a JCombo box and images.
  2. Use of a GUI Builder is prohibited.
  3. Download the image file, it provides images and a framework of the code (incomplete code).
  4. The lab requires two classes
    1. ComboBoxTest - provided
    2. ComboBoxFrame - partially provided
      1. Constructor -
        1. set the Frame layout type - FlowLayout is fine, but any layout type is acceptable
        2. Creates JComboBox from array of image names
        3. Creates an inner class
          1. handles the JComboBox events
          2. Displays correct image in the classes JLabel
          3. NOTE: get and image use new ImageIcon( getClass().getResource( selection ), where selection is the image file's name.
      2. You may break this into methods if you like or do all the work in the constructor.
      3. See examples ComboBoxWindow and MyCatImage in the additional example downloads as need.
  5. This lab can be completed using the standard ActionListeners however, it can also be completed using the ItemListener class. If you feel adventurous, explore the API and/or other resources and use the ItemListener class.
  6. Make sure you Javadoc your classes.
0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images;
    String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
    public CustomComboBoxDemo() {
        super(new BorderLayout());
        images = new ImageIcon[petStrings.length];
        Integer[] intArray = new Integer[petStrings.length];
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("images/" + petStrings[i] + ".gif");
            if (images[i] != null) {
                images[i].setDescription(petStrings[i]);
            }
        }

        JComboBox petList = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        renderer.setPreferredSize(new Dimension(200, 130));
        petList.setRenderer(renderer);
        petList.setMaximumRowCount(3);
        add(petList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("CustomComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JComponent newContentPane = new CustomComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            int selectedIndex = ((Integer)value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            ImageIcon icon = images[selectedIndex];
            String pet = petStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(pet);
                setFont(list.getFont());
            } else {
                setUhOhText(pet + " (no image available)",
                            list.getFont());
            }

            return this;
        }
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}
Add a comment
Know the answer?
Add Answer to:
Activity: Build a simple GUI application using a JCombo box and images. Use of a GUI Builder is ...
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
  • i want answers please ??? Answers to Self-Review Exercises 625 14.3 d) In a BorderLayout, two...

    i want answers please ??? Answers to Self-Review Exercises 625 14.3 d) In a BorderLayout, two buttons added to the NORTH region will be placed side by side. e) A maximum of five components can be added to a BorderLayout ) Inner classes are not allowed to access the members of the enclosing class. B) A TextArea's text is always read-only. h) Class TextArea is a direct subclass of class Component. Find the error(s) in each of the following statements,...

  • Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout...

    Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout to add buttons to start each sort and display the System.nanoTime in common TextArea panel. The question is a bit confusing so i will try to simplify it. Using the GUI ( I made a unclick able one so you have to make it clickable), allow a user to sort the text file based on what they click on. example: if i click merge...

  • Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one me...

    Please try to write the code with Project 1,2 and 3 in mind. And use java language, thank you very much. Create an Edit Menu in your GUI Add a second menu to the GUI called Edit which will have one menu item called Search. Clicking on search should prompt the user using a JOptionPane input dialog to enter a car make. The GUI should then display only cars of that make. You will need to write a second menu...

  • Java FX Application Purpose The purpose of this assignment is to get you familiar with the...

    Java FX Application Purpose The purpose of this assignment is to get you familiar with the basics of the JavaFX GUI interface components. This assignment will cover Labels, Fonts, Basic Images, and Layouts. You will use a StackPane and a BorderPane to construct the layout to the right. In addition you will use the Random class to randomly load an image when the application loads Introduction The application sets the root layout to a BorderPane. The BorderPane can be divided...

  • In java language here is my code so far! i only need help with the extra...

    In java language here is my code so far! i only need help with the extra credit part For this project, you will create a Rock, Paper, Scissors game. Write a GUI program that allows a user to play Rock, Paper, Scissors against the computer. If you’re not familiar with Rock, Paper, Scissors, check out the Wikipedia page: http://en.wikipedia.org/wiki/Rock-paper-scissors This is how the program works: The user clicks a button to make their move (rock, paper, or scissors). The program...

  • Project overview: Create a java graphics program that displays an order menu and bill from a...

    Project overview: Create a java graphics program that displays an order menu and bill from a Sandwich shop, or any other establishment you prefer. In this program the design is left up to the programmer however good object oriented design is required. Below are two images that should be used to assist in development of your program. Items are selected on the Order Calculator and the Message window that displays the Subtotal, Tax and Total is displayed when the Calculate...

  • ArrayQueue

    Implement the ArrayQueue classIn the ‘Queues’ lecture, review the ‘Introduce next lab’ section.  See here that we can use a circular array to implement the queue data structure.  You must write a class named ArrayQueue that does this.ArrayQueue will be a generic class, that implements our generic QueueInterface interface.  This demonstrates the Java interface feature, where we have already implemented queue dynamically, using the LinkedQueue class covered during the lecture.Many classes are given to youDownload and unzip the Circular array project from Canvas, ‘Queues’ module, Example programs.  Open the project in...

  • the first question java code eclipse app the second question is java fx gui caculator please...

    the first question java code eclipse app the second question is java fx gui caculator please fast 1. Create project called "YourFirstName_QUID'. Eg. Aliomar_202002345 2. Create two package Q1 and Q2. 3. Add your name and studentID as comments on the top of each Java source file you submit. Question 1. Bookings APP [80 Points-six parts] Implement the following hotel booking system. Use the following class diagram to understand the structure of the system's classes, their attributes operations (or methods),...

  • Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a...

    Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a queue. Then you are going to use the queue to store animals. 1. Write a LinkedQueue class that implements the QueueADT.java interface using links. 2. Textbook implementation uses a count variable to keep track of the elements in the queue. Don't use variable count in your implementation (points will be deducted if you use instance variable count). You may use a local integer variable...

  • JAVA Hello I am trying to add a menu to my Java code if someone can...

    JAVA Hello I am trying to add a menu to my Java code if someone can help me I would really appreacite it thank you. I found a java menu code but I dont know how to incorporate it to my code this is the java menu code that i found. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class MenuExp extends JFrame { public MenuExp() { setTitle("Menu Example");...

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