Turn on thread page Beta
    • Community Assistant
    • Very Important Poster
    • Thread Starter
    Offline

    20
    ReputationRep:
    Community Assistant
    Very Important Poster
    I am struggling so much with the software development module on my degree, and I need some resources to use in order to create my GUI.

    I am confused as to where to make a new frame, like do I make a new class with a main method? but then how do I link the product class to that class? BASICALLY, IM SO CONFUSED and stressed to the point where I am willing to pay to get a Java tutor just so I can master it.

    My task is to create a "basic" GUI which records product information (it should update stock levels, reprice products and sells products):

    I've made a Product abstract class so far:
    Code:
    public abstract class Product {
    
    //attributes to store product information
    private String name;
    private int stockLevel;
    private double price;
    
    //constructor - intialisation of variables
    
    public Product (String nameIn, int stockLevelIn, double priceIn)
    {
    name = nameIn;
    stockLevel = stockLevelIn;
    price = priceIn;
    }
    
    // methods - functions
    public int reStock(int newStockLevel)
    {
    return newStockLevel;
    }
    
    public double sell (int sellItems)
    {
    return sellItems;
    }
    
    public void setPrice (double resetPrice)
    {
    resetPrice = price;
    }
    
    public String getName ()
    {
    return name;
    }
    
    public int getStockLevel()
    { 
     return stockLevel;
    }
    
    public double getPrice()
    {
    return price;
    }
    
    }
    Offline

    18
    ReputationRep:
    You mentioned 'Frame', so I'm guessing you're using the older Swing components for your GUI instead of the newer 'JavaFX' components?

    Do you have a book which explains how Java Swing works? Have you created any GUIs using Swing before?

    To answer your question - yes you should definitely create a new JFrame (derived class), and no - don't give it a main method.

    I would suggest copying the "Hello World" example from the official docs here - it's a good starting point that gives you some basic "stuff" to get a super-simple GUI up and running which you can add to later: https://docs.oracle.com/javase/tutor...orldSwing.java

    There are loads of examples using various specific Swing components here: https://docs.oracle.com/javase/tutor...nts/index.html

    Just a few points worth remembering when you're creating a GUI in Swing:
    • All GUIs in Swing are made out of Component instances. A Component instance is any instance whose class derives from the top-level Component class - that could be a built-in class, or one that you have derived from one of those classes yourself.
    • Component instances are just plain old regular objects - i.e. they are instances based on a class, created with the new keyword, etc.
    • A GUI is basically a Component which contains a lot of other nested Component (a.k.a "composite", which in turn might contain some more Components, etc.
    • A JFrame is a Container Component, which includes a Layout Manager (by default, it uses BorderLayout which has different areas - NORTH, SOUTH, CENTER, etc.) - see the JFrame docs - https://docs.oracle.com/javase/7/doc...ng/JFrame.html
    • You can (and often should) make your own Componentclass(es) by inheriting from exising Swing classes if you want to create more complex GUIs - for example, you should ideally create a JFrame-derived class which contain some JPanelsusing various different layouts which contain editable text boxes, some kind of output display, buttons, etc.

    Here's a super simple program with a GUI written in a class derived from JFrame which holds the data for a single animal, and a simple toString override which the UI can use:

    Animal.java :
    Code:
    public class Animal {
        public String name;
        public String species;
    
        @Override
        public String toString() {
            return name + " " + species;
        }
    }
    Now, consider creating a new class derived from JFrame to hold your UI. Here's a very simple layout with a few inputs and a couple of buttons:

    AnimalFrame.java:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    
    public class AnimalFrame extends JFrame {
        // Components
        public final JTextField nameTextField = new JTextField();
        public final JTextField speciesTextField = new JTextField();
        public final JButton addButton = new JButton("Add");
        public final JButton resetButton = new JButton("Reset");
        public final DefaultListModel animalList = new DefaultListModel();
    
        public AnimalFrame(){
            super("Animal Manager");
    
            // Input fields
            JPanel inputPanel = new JPanel(new GridLayout(2,2));
            inputPanel.add(new JLabel("Name"));
            inputPanel.add(nameTextField);
            inputPanel.add(new JLabel("Species"));
            inputPanel.add(speciesTextField);
            this.add(inputPanel, BorderLayout.NORTH);
    
            // Buttons
            JPanel buttonPanel = new JPanel(new FlowLayout());
            buttonPanel.add(resetButton);
            buttonPanel.add(addButton);
            this.add(buttonPanel, BorderLayout.CENTER);
    
            // Scrollable List
            JPanel listPanel = new JPanel();
            JScrollPane scrollPane = new JScrollPane();
            JList list = new JList(animalList);
            list.setVisibleRowCount(4);
            scrollPane.setViewportView(list);
            listPanel.add(scrollPane);
            this.add(listPanel, BorderLayout.SOUTH);
    
            // Button click events
            this.addButton.addActionListener(this::onAddButtonClicked);
            this.resetButton.addActionListener(this::onResetButtonClicked);
        }
    
        private void onAddButtonClicked(ActionEvent e) {
            Animal animal = new Animal();
            animal.name = this.nameTextField.getText();
            animal.species = this.speciesTextField.getText();
            this.animalList.addElement(animal);
        }
    
        private void onResetButtonClicked(ActionEvent e) {
            this.animalList.removeAllElements();
        }
    }
    Lastly, here's a test class with a 'main' method which runs the UI:

    Test.java:
    Code:
    import javax.swing.*;
    
    public class Test {
    
        private static void createAndShowGUI() {
            AnimalFrame frame = new AnimalFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(Test::createAndShowGUI);
        }
    }
    Have a look closely at the AnimalFrame class to see how the layout is set up:
    • There are two JTextFields UI components in a JPanel called nameTextField and speciesTextField
    • There's a JList UI component with a JScrollPane component in another JPanel with a DefaultListModel called animalList.
    • Finally, there are two JButton UI components in a JPanel called addButton and resetButton.

    Now look to see how the UI actually works:
    • addButton has a "listener" which is a method called onAddButtonClicked Clicked .
    • resetButton has a "listener" which is a method called onResetButtonClicked Clicked .
    • When the 'add' button is clicked, it creates an Animal instance, using the text fields on the UI, and pushes that instance into the list
    • when the 'reset' button is clicked, it clears the list.


    Unfortunately there aren't really many great free tutorials out there for Java Swing, because it's a bit old, a lot of the free online Java courses seem to use JavaFX. But the official tutorial is still pretty decent, and definitely worth using as a reference to figure out how to use all the various components: https://docs.oracle.com/javase/tutorial/uiswing/

    There's a swing course on Udemy which is fairly cheap though: https://www.udemy.com/java-swing-complete/

    And to be honest, you should be able to google around and look on StackOverflow for loads of questions and answers about different ways to use Swing - all the information is out there, you just have to dig for it
    • Community Assistant
    • Very Important Poster
    • Thread Starter
    Offline

    20
    ReputationRep:
    Community Assistant
    Very Important Poster
    winterscoming


    Thank you so much for your help once again!
    Offline

    18
    ReputationRep:
    (Original post by squirrology)
    winterscoming


    Thank you so much for your help once again!
    You're welcome. Swing is actually a bit old, so it can be a bit of a pain, so don't worry if you find it awkward to use, you're definitely not the only one! In particular, the whole LayoutManager thing using Swing's built-in Layout s (GridLayout, BorderLayout, FlowLayout, etc.) can feel really limiting, and unfortunately you just have to suck it up. Hopefully your teacher already realises this and won't penalise you for a messy looking UI. It might help to know what you can and can't easily do with those Layouts though, if you haven't seen this page already - https://docs.oracle.com/javase/tutor...out/index.html

    So aside from layouts (and "nested" layouts - e.g. putting FlowLayouts inside a GridLayout), Most GUI stuff should be fairly easy to understand. Things like button clicks and text boxes are straightforward, so with a bit of practice you should be fine. I find the best way to understand it is by copying examples from the documentation or StackOverflow and figuring out how they work, tinkering with them until they do whatever you're trying to do. The most important thing is getting the basic understanding. Once you understand it, you're good to go - there's no point trying to memorise all the different components and methods
 
 
 
Reply
Submit reply
Turn on thread page Beta
Updated: March 10, 2018

1,162

students online now

800,000+

Exam discussions

Find your exam discussion here

Poll
Should universities take a stronger line on drugs?

The Student Room, Get Revising and Marked by Teachers are trading names of The Student Room Group Ltd.

Register Number: 04666380 (England and Wales), VAT No. 806 8067 22 Registered Office: International House, Queens Road, Brighton, BN1 3XE

Write a reply...
Reply
Hide
Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.