Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8842983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T11:06:10+00:00 2026-06-14T11:06:10+00:00

I’m trying to add a restart/replay functionality to my Java game. Currently in my

  • 0

I’m trying to add a restart/replay functionality to my Java game.
Currently in my Game class (where the GUI and game gets initialized), I have:

init() method
Game() object

The Game object contains the GUI for the whole game window, and includes various objects (such as the actual game window, score board, a countdown timer, etc).

I would like to add a functionality where the game would restart (along with the countdown and scoring) if they click the restart button on the GUI or once the game ends.
I do realize that it’s best to re-instantiate the objects (scoring, countdown), however once instantiated they’re part of my GUI

i.e. add(scoreboard)

Is there a way to re-instantiate the objects without having to re-instantiate my GUI? Ideally I’d just like to re-instantiate the objects without having to re-open a completely new JFrame for the GUI. If someone could provide me with a sort of outline for the classes and methods I should have (and what they do), it’d be much appreciated.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T11:06:11+00:00Added an answer on June 14, 2026 at 11:06 am

    Separate the data (model) from the GUI (view).

    To take one example, your scoreboard is probably a JTable. The JTable would be in a view class, while the TableModel would be in a model class.

    You do the same for all of your GUI components. For each component, you have a model of the component data in a model class.

    Here’s a model class for a stopwatch GUI I put together. Without even seeing the GUI, you should be able to identify all of the data components that make up a stop watch.

    package com.ggl.stopwatch.model;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.table.DefaultTableModel;
    
    public class StopwatchModel {
    
        protected boolean isSplitTime;
    
        protected long startTime;
    
        protected long endTime;
    
        protected DefaultTableModel tableModel;
    
        protected List<Long> splitTimes;
    
        protected String[] columnNames = {"", "Increment", "Cumulative"};
    
        public StopwatchModel() {
            this.splitTimes = new ArrayList<Long>();
            this.isSplitTime = false;
            this.startTime = 0;
            this.endTime = 0;
            setTableModel();
        }
    
        public void resetTimes() {
            this.splitTimes.clear();
            this.isSplitTime = false;
            this.startTime = 0;
            this.endTime = 0;
        }
    
        public boolean isSplitTime() {
            return isSplitTime;
        }
    
        public long getStartTime() {
            return startTime;
        }
    
        public long getEndTime() {
            return endTime;
        }
    
        public long getLastSplitTime() {
            int size = splitTimes.size();
            if (size < 1) {
                return getStartTime();
            } else {
                return splitTimes.get(size - 1);
            }
        }
    
        public long getPenultimateSplitTime() {
            int size = splitTimes.size();
            if (size < 2) {
                return getStartTime();
            } else {
                return splitTimes.get(size - 2);
            }
        }
    
        public DefaultTableModel getTableModel() {
            return tableModel;
        }
    
        public int getTableModelRowCount() {
            return tableModel.getRowCount();
        }
    
        public void clearTableModel() {
            tableModel.setRowCount(0);
        }
    
        public int addTableModelRow(long startTime, long previousSplitTime, 
                long currentSplitTime, int splitCount) {
            String[] row = new String[3];
    
            row[0] = "Split " + ++splitCount;
            row[1] = formatTime(previousSplitTime, currentSplitTime, false);
            row[2] = formatTime(startTime, currentSplitTime, false);
    
            tableModel.addRow(row);
    
            return splitCount;
        }
    
        public void setStartTime() {
            if (getStartTime() == 0L) {
                this.startTime = System.currentTimeMillis();
            } else {
                long currentTime = System.currentTimeMillis();
                int size = splitTimes.size();
                if (size > 0) {
                    long splitTime = splitTimes.get(size - 1);
                    splitTime = splitTime - getEndTime() + currentTime;
                    splitTimes.set(size - 1, splitTime);
                }
                this.startTime = currentTime - getEndTime() + getStartTime();
            }
        }
    
        protected void setTableModel() {
            this.tableModel = new DefaultTableModel();
            this.tableModel.addColumn(columnNames[0]);
            this.tableModel.addColumn(columnNames[1]);
            this.tableModel.addColumn(columnNames[2]);
        }
    
        public void setSplitTime() {
            this.splitTimes.add(System.currentTimeMillis());
            isSplitTime = true;
        }
    
        public void setEndTime() {
            Long split = System.currentTimeMillis();
            if (isSplitTime) {
                this.splitTimes.add(split);
            }
            this.endTime = split;
        }
    
        public String formatTime(long startTime, long time, boolean isTenths) {
            long elapsedTime = time - startTime;
    
            int seconds = (int) (elapsedTime / 1000L);
    
            int fraction = (int) (elapsedTime - ((long) seconds * 1000L));
            fraction = (fraction + 5) / 10;
            if (fraction > 99) {
                fraction = 0;
            }
            if (isTenths) {
                fraction = (fraction + 5) / 10;
                if (fraction > 9) {
                    fraction = 0;
                }
            }
    
    
            int hours = seconds / 3600;
            seconds -= hours * 3600;
    
            int minutes = seconds / 60;
            seconds -= minutes * 60;
    
            StringBuilder builder = new StringBuilder();
    
            builder.append(hours);
            builder.append(":");
            if (minutes < 10) builder.append("0");
            builder.append(minutes);
            builder.append(":");
            if (seconds < 10) builder.append("0");
            builder.append(seconds);
            builder.append(".");
            if ((!isTenths) && (fraction < 10)) builder.append("0");
            builder.append(fraction);
    
            return builder.toString();
        }
    
    }
    

    Once separated, you put initialize methods in your model classes.

    Edited to add: You pass an instance of the model class to your view class to generate the view. Here’s the main panel of the stop watch GUI.

    package com.ggl.stopwatch.view;
    
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    
    import com.ggl.stopwatch.model.StopwatchModel;
    import com.ggl.stopwatch.thread.StopwatchThread;
    
    public class StopwatchPanel {
    
        protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
        protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);
    
        protected JButton resetButton;
        protected JButton startButton;
        protected JButton splitButton;
        protected JButton stopButton;
    
        protected JLabel timeDisplayLabel;
    
        protected JPanel mainPanel;
        protected JPanel buttonPanel;
        protected JPanel startPanel;
        protected JPanel stopPanel;
    
        protected SplitScrollPane splitScrollPane;
    
        protected StopwatchModel model;
    
        protected StopwatchThread thread;
    
        public StopwatchPanel(StopwatchModel model) {
            this.model = model;
            createPartControl();
        }
    
        protected void createPartControl() {
            splitScrollPane = new SplitScrollPane(model);
    
            createStartPanel();
            createStopPanel();
            setButtonSizes(resetButton, startButton, splitButton, stopButton);
    
            mainPanel = new JPanel();
            mainPanel.setLayout(new GridBagLayout());
    
            int gridy = 0;
    
            JPanel displayPanel = new JPanel();
            displayPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 6));
    
            timeDisplayLabel = new JLabel(model.formatTime(0L, 0L, true));
            timeDisplayLabel.setHorizontalAlignment(SwingConstants.CENTER);
            Font font = timeDisplayLabel.getFont();
            Font labelFont = font.deriveFont(60.0F);
            timeDisplayLabel.setFont(labelFont);
            timeDisplayLabel.setForeground(Color.BLUE);
            displayPanel.add(timeDisplayLabel);
    
            addComponent(mainPanel, displayPanel, 0, gridy++, 1, 1, spaceInsets,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
    
            buttonPanel = new JPanel();
            buttonPanel.add(startPanel);
            addComponent(mainPanel, buttonPanel, 0, gridy++, 1, 1, spaceInsets,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
    
            addComponent(mainPanel, splitScrollPane.getSplitScrollPane(), 0, gridy++, 1, 1, spaceInsets,
                    GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
        }
    
        protected void createStartPanel() {
            startPanel = new JPanel();
            startPanel.setLayout(new FlowLayout());
    
            resetButton = new JButton("Reset");
            resetButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    model.resetTimes();
                    timeDisplayLabel.setText(model.formatTime(0L, 0L, true));
                    splitScrollPane.clearPanel();
                    mainPanel.repaint();
                }
            });
    
            startPanel.add(resetButton);
    
            startButton = new JButton("Start");
            startButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    model.setStartTime();
                    thread = new StopwatchThread(StopwatchPanel.this);
                    thread.start();
                    displayStopPanel();
                }
            });
    
            startPanel.add(startButton);
        }
    
        protected void createStopPanel() {
            stopPanel = new JPanel();
            stopPanel.setLayout(new FlowLayout());
    
            splitButton = new JButton("Split");
            splitButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    model.setSplitTime();
                    splitScrollPane.addSplit(model.getStartTime(), 
                            model.getPenultimateSplitTime(), 
                            model.getLastSplitTime());
                    splitScrollPane.setMaximum();
                    splitScrollPane.repaint();
                }
            });
    
            stopPanel.add(splitButton);
    
            stopButton = new JButton("Stop");
            stopButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    model.setEndTime();
                    thread.setRunning(false);
                    if (model.isSplitTime()) {
                        splitScrollPane.addSplit(model.getStartTime(), 
                                model.getPenultimateSplitTime(), 
                                model.getLastSplitTime());
                        splitScrollPane.setMaximum();
                        splitScrollPane.repaint();
                    }
                    displayStartPanel();
                }
            });
    
            stopPanel.add(stopButton);
        }
    
        protected void addComponent(Container container, Component component,
                int gridx, int gridy, int gridwidth, int gridheight, 
                Insets insets, int anchor, int fill) {
            GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
                    gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
            container.add(component, gbc);
        }
    
        protected void displayStopPanel() {
            buttonPanel.remove(startPanel);
            buttonPanel.add(stopPanel);
            buttonPanel.repaint();
        }
    
        protected void displayStartPanel() {
            buttonPanel.remove(stopPanel);
            buttonPanel.add(startPanel);
            buttonPanel.repaint();
        }
    
        protected void setButtonSizes(JButton ... buttons) {
            Dimension preferredSize = new Dimension();
            for (JButton button : buttons) {
                Dimension d = button.getPreferredSize();
                preferredSize = setLarger(preferredSize, d);
            }
            for (JButton button : buttons) {
                button.setPreferredSize(preferredSize);
            }
        }
    
        protected Dimension setLarger(Dimension a, Dimension b) {
            Dimension d = new Dimension();
            d.height = Math.max(a.height, b.height);
            d.width = Math.max(a.width, b.width);
            return d;
        }
    
        public void setTimeDisplayLabel() {
            this.timeDisplayLabel.setText(model.formatTime(model.getStartTime(), 
                    System.currentTimeMillis(), true));
        }
    
        public JPanel getMainPanel() {
            return mainPanel;
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have been unable to fix a problem with Java Unicode and encoding. The
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.