Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Issues With Layout And Time Being Display

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Issues With Layout And Time Being Display

    Currently doing an assignment for college that involves displaying multiple "clocks" on screen depending on how many cities are selected from a list.

    I have most of it built I believe but I am having a couple of issues that I hope someone can give me advice on.

    1. Having selected a couple of cities from the list, when I press the "+" button on the display they get added to the list horizontally. I am trying to get them to be added vertically. I believe I have set the layout to a grid layout with 1 column and a number of rows depending on how many cities are selected from the list so not sure why that is happening.

    2. What I am trying to achieve is that when the "+" button is pressed, the panel that is going to contain the "clocks" is wipped clear and only the cities that I have selected are going to have their "clocks" displayed. Can you achieve this with a jpanel? I know I could do something like this with a jtextarea by setting the text to an empty string. Is there something similar for a jpanel?

    3. When I have multiple clocks being displayed, only the last clock added updates its time. I want all the clocks that I have displayed to be ticking away when displayed. Can you point me in the right direction as to what I am leaving out of the code to achieve this?

    I have though about building a clock interface for each of the cities in advance and setting them visible / invisible as needed but I want to be able to add cities to the list without having to also go and build a clock for that city.

    Any help or advice would be much appreciated.

    This is what I have done with my code so far...

    import java.awt.*;  
    import javax.swing.*;  
    import java.awt.event.*;  
    import javax.swing.event.*;  
    import java.util.Date;  
    import java.text.SimpleDateFormat;  
     
    public class AssignmentV1 implements ActionListener/*,ListSelectionListener*/ 
    { 
        private String [] cities; 
        private JButton addBtn; 
        private JButton minusBtn; 
        private JList cityList; 
        private JPanel right; 
        private JPanel displayArea;
        private JPanel [] clockDisplay;
        private long currentTime;
        private long cityTime;
        private int hourDiff;
        private String cityName;
        private String timeInFormat;
        private JLabel time;
        private JPanel topRight;
        public AssignmentV1() 
        { 
            JFrame appWin = new JFrame("World Time");  
            appWin.setSize(400,400);  
            appWin.setLocationRelativeTo(null);  
            appWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     
            Font preferredFont = new Font("OCR A EXTENDED",Font.BOLD,50);  
     
            Container contentPane =appWin.getContentPane();  
     
            displayArea = new JPanel();  
            displayArea.setLayout(new GridLayout(1,2));  
     
            JPanel left = new JPanel();  
            left.setLayout(new GridLayout(2,1));  
     
            JPanel topLeft = new JPanel();  
            topLeft.setLayout(new FlowLayout(FlowLayout.CENTER));  
            //adding of +/- buttons to display 
            addBtn = new JButton();  
            addBtn.setText("+");  
            addBtn.addActionListener(this);  
            topLeft.add(addBtn);  
            minusBtn = new JButton();  
            minusBtn.setText("-");
            minusBtn.addActionListener(this);  
            topLeft.add(minusBtn);  
            left.add(topLeft);  
     
            //adding of list of cities to a scrollpane to add to display    
            JPanel bottomLeft=new JPanel(); 
     
            setUpCities(); 
            cityList=new JList(cities);    
            cityList.setSelectedIndex(0); 
            cityList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
            JScrollPane scrollableList = new JScrollPane(cityList);  
            bottomLeft.add(scrollableList);  
            left.add(bottomLeft);  
     
            right = new JPanel();
            topRight = new JPanel();
            clockDisplay = new JPanel[1];
            topRight.setLayout(new GridLayout(clockDisplay.length,1));
            for(int i=0;i<clockDisplay.length;i++)
            {
                clockDisplay[i]=new JPanel();
                cityName = cities[0].substring(0,cities[0].indexOf(","));
                hourDiff=Integer.parseInt(cities[0].substring(cities[0].indexOf(",")+1));
                currentTime = System.currentTimeMillis();
                cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                time = new JLabel();
                time.setOpaque(true);
                timeInFormat = textAsTime(cityTime);
                time.setText(timeInFormat);
                clockDisplay[i].add(time);
                topRight.add(clockDisplay[i]);
            }
            right.add(topRight);
     
     
            displayArea.add(left);  
            displayArea.add(right);  
            contentPane.add(displayArea);   
            Timer t= new Timer(1000,this);
            t.start();
            appWin.setVisible(true);
     
        } 
        public void actionPerformed(ActionEvent e)  
        {
            cityTime=cityTime+1000;
            timeInFormat=textAsTime(cityTime);
            time.setText(timeInFormat);
     
            Object [] obj = cityList.getSelectedValues();
            Object source=e.getSource();
            if(source==addBtn)
            {
                right.setLayout(new GridLayout(obj.length,1));
                clockDisplay = new JPanel[obj.length];
                topRight.setLayout(new GridLayout(obj.length,1));
                for(int i=0;i<obj.length;i++)
                {
                    String temp = (String)obj[i];
                    clockDisplay[i]=new JPanel();
                    cityName = temp.substring(0,temp.indexOf(","));
                    hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
                    currentTime = System.currentTimeMillis();
                    cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                    clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                    time = new JLabel();
                    time.setOpaque(true);
                    timeInFormat = textAsTime(cityTime);
                    time.setText(timeInFormat);
                    clockDisplay[i].add(time);
                    topRight.add(clockDisplay[i]);
                }
                right.add(topRight);
            }
        }
        public void setUpCities() 
        { 
           cities = new String []{"Accra,0","Addis Abada,+3","Adelaide,+11","Algiers,-1","Almaty,+6","Amman,+3","Amsterdam,+1","Anadyr,+12","Anchorage,-8","Ankara,+2","London,0","Paris,+1"};         
        } 
        public String textAsTime(long currentTime)  
        {  
            long second = (currentTime / 1000) % 60; 
            long minute = (currentTime / (1000 * 60)) % 60; 
            long hour = (currentTime / (1000 * 60 * 60)) % 24; 
            return String.format("%02d:%02d:%02d",hour,minute,second);  
        }        
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    Do you have a main() method for testing the code?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    sorry, haven't created one yet, using BlueJ and just creating new instances of it

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    Ok, no hurry. I'll wait.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    updated with a main method now...

    import java.awt.*;  
    import javax.swing.*;  
    import java.awt.event.*;  
    import javax.swing.event.*;  
    import java.util.Date;  
    import java.text.SimpleDateFormat;  
     
    public class AssignmentV1 implements ActionListener/*,ListSelectionListener*/ 
    { 
        private String [] cities; 
        private JButton addBtn; 
        private JButton minusBtn; 
        private JList cityList; 
        private JPanel right; 
        private JPanel displayArea;
        private JPanel [] clockDisplay;
        private long currentTime;
        private long cityTime;
        private int hourDiff;
        private String cityName;
        private String timeInFormat;
        private JLabel time;
        private JPanel topRight;
        public AssignmentV1() 
        { 
            JFrame appWin = new JFrame("World Time");  
            appWin.setSize(400,400);  
            appWin.setLocationRelativeTo(null);  
            appWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     
            Font preferredFont = new Font("OCR A EXTENDED",Font.BOLD,50);  
     
            Container contentPane =appWin.getContentPane();  
     
            displayArea = new JPanel();  
            displayArea.setLayout(new GridLayout(1,2));  
     
            JPanel left = new JPanel();  
            left.setLayout(new GridLayout(2,1));  
     
            JPanel topLeft = new JPanel();  
            topLeft.setLayout(new FlowLayout(FlowLayout.CENTER));  
            //adding of +/- buttons to display 
            addBtn = new JButton();  
            addBtn.setText("+");  
            addBtn.addActionListener(this);  
            topLeft.add(addBtn);  
            minusBtn = new JButton();  
            minusBtn.setText("-");
            minusBtn.addActionListener(this);  
            topLeft.add(minusBtn);  
            left.add(topLeft);  
     
            //adding of list of cities to a scrollpane to add to display    
            JPanel bottomLeft=new JPanel(); 
     
            setUpCities(); 
            cityList=new JList(cities);    
            cityList.setSelectedIndex(0); 
            cityList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
            JScrollPane scrollableList = new JScrollPane(cityList);  
            bottomLeft.add(scrollableList);  
            left.add(bottomLeft);  
     
            right = new JPanel();
            topRight = new JPanel();
            clockDisplay = new JPanel[1];
            topRight.setLayout(new GridLayout(clockDisplay.length,1));
            for(int i=0;i<clockDisplay.length;i++)
            {
                clockDisplay[i]=new JPanel();
                cityName = cities[0].substring(0,cities[0].indexOf(","));
                hourDiff=Integer.parseInt(cities[0].substring(cities[0].indexOf(",")+1));
                currentTime = System.currentTimeMillis();
                cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                time = new JLabel();
                time.setOpaque(true);
                timeInFormat = textAsTime(cityTime);
                time.setText(timeInFormat);
                clockDisplay[i].add(time);
                topRight.add(clockDisplay[i]);
            }
            right.add(topRight);
     
     
            displayArea.add(left);  
            displayArea.add(right);  
            contentPane.add(displayArea);   
            Timer t= new Timer(1000,this);
            t.start();
            appWin.setVisible(true);
     
        } 
        public void actionPerformed(ActionEvent e)  
        {
            cityTime=cityTime+1000;
            timeInFormat=textAsTime(cityTime);
            time.setText(timeInFormat);
     
            Object [] obj = cityList.getSelectedValues();
            Object source=e.getSource();
            if(source==addBtn)
            {
                right.setLayout(new GridLayout(obj.length,1));
                clockDisplay = new JPanel[obj.length];
                topRight.setLayout(new GridLayout(obj.length,1));
                for(int i=0;i<obj.length;i++)
                {
                    String temp = (String)obj[i];
                    clockDisplay[i]=new JPanel();
                    cityName = temp.substring(0,temp.indexOf(","));
                    hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
                    currentTime = System.currentTimeMillis();
                    cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                    clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                    time = new JLabel();
                    time.setOpaque(true);
                    timeInFormat = textAsTime(cityTime);
                    time.setText(timeInFormat);
                    clockDisplay[i].add(time);
                    topRight.add(clockDisplay[i]);
                }
                right.add(topRight);
            }
        }
        public void setUpCities() 
        { 
           cities = new String []{"Accra,0","Addis Abada,+3","Adelaide,+11","Algiers,-1","Almaty,+6","Amman,+3","Amsterdam,+1","Anadyr,+12","Anchorage,-8","Ankara,+2","London,0","Paris,+1"};         
        } 
        public String textAsTime(long currentTime)  
        {  
            long second = (currentTime / 1000) % 60; 
            long minute = (currentTime / (1000 * 60)) % 60; 
            long hour = (currentTime / (1000 * 60 * 60)) % 24; 
            return String.format("%02d:%02d:%02d",hour,minute,second);  
        }
        public static void main(String [] args)
        {
            new AssignmentV1();
        }
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    How are each of the clock's displays handled so that each can be updated?
    I expect to see a collection of some kind where the displays are saved so that the timer can go through the displays saved in the collection and up date them one by one.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    at the moment they are not.
    are you suggesting about adding the individual times to a list as they are generated in the actionPerformed method?
    and then perform the an update on them ie (+1000 milliseconds)
    I will try that and see if helps.
    Thanks

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    There needs to be a list of the labels to be updated. The current code has a single reference to a label to be updated.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    sorry, it does not seem to be working for me. I have created two array lists, one to store the names of the cities selected(I am thinking I may need this when I move onto the other part of the project where I am going to have to remove clocks using the "-" button but that is for another day) and the other to store the time at the city.
    I have also introduced a method, tick which moves on the current time by 1 sec however I am still getting the same problem with the other clocks stopping as soon as I introduce another one. I must not be fully understanding what you are trying to explain?
    import java.awt.*;
    import java.util.ArrayList; 
    import javax.swing.*;  
    import java.awt.event.*;  
    import javax.swing.event.*;  
    import java.util.Date;  
    import java.text.SimpleDateFormat;  
     
    public class AssignmentV1 implements ActionListener/*,ListSelectionListener*/ 
    { 
        private String [] cities; 
        private JButton addBtn; 
        private JButton minusBtn; 
        private JList cityList; 
        private JPanel right; 
        private JPanel displayArea;
        private JPanel [] clockDisplay;
        private long currentTime;
        private long cityTime;
        private int hourDiff;
        private String cityName;
        private String timeInFormat;
        private JLabel time;
        private JPanel topRight;
        private ArrayList<String> cityNamesList;
        private ArrayList<Long> cityTimes;
        public AssignmentV1() 
        { 
            JFrame appWin = new JFrame("World Time");  
            appWin.setSize(400,400);  
            appWin.setLocationRelativeTo(null);  
            appWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     
            Font preferredFont = new Font("OCR A EXTENDED",Font.BOLD,50);  
     
            Container contentPane =appWin.getContentPane();  
     
            displayArea = new JPanel();  
            displayArea.setLayout(new GridLayout(1,2));  
     
            JPanel left = new JPanel();  
            left.setLayout(new GridLayout(2,1));  
     
            JPanel topLeft = new JPanel();  
            topLeft.setLayout(new FlowLayout(FlowLayout.CENTER));  
            //adding of +/- buttons to display 
            addBtn = new JButton();  
            addBtn.setText("+");  
            addBtn.addActionListener(this);  
            topLeft.add(addBtn);  
            minusBtn = new JButton();  
            minusBtn.setText("-");
            minusBtn.addActionListener(this);  
            topLeft.add(minusBtn);  
            left.add(topLeft);  
     
            //adding of list of cities to a scrollpane to add to display    
            JPanel bottomLeft=new JPanel(); 
     
            setUpCities(); 
            cityList=new JList(cities);    
            cityList.setSelectedIndex(0); 
            cityList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
            JScrollPane scrollableList = new JScrollPane(cityList);  
            bottomLeft.add(scrollableList);  
            left.add(bottomLeft);  
     
            right = new JPanel();
            topRight = new JPanel();
            clockDisplay = new JPanel[1];
            topRight.setLayout(new GridLayout(clockDisplay.length,1));
            for(int i=0;i<clockDisplay.length;i++)
            {
                clockDisplay[i]=new JPanel();
                cityName = cities[0].substring(0,cities[0].indexOf(","));
                hourDiff=Integer.parseInt(cities[0].substring(cities[0].indexOf(",")+1));
                currentTime = System.currentTimeMillis();
                cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                time = new JLabel();
                time.setOpaque(true);
                timeInFormat = textAsTime(cityTime);
                time.setText(timeInFormat);
                clockDisplay[i].add(time);
                topRight.add(clockDisplay[i]);
            }
            right.add(topRight);
     
     
            displayArea.add(left);  
            displayArea.add(right);  
            contentPane.add(displayArea);   
            Timer t= new Timer(1000,this);
            t.start();
            appWin.setVisible(true);
     
        } 
        public void actionPerformed(ActionEvent e)  
        {
            cityTime = tick(cityTime);
            timeInFormat=textAsTime(cityTime);
            time.setText(timeInFormat);
            cityNamesList = new ArrayList<String>();
            cityTimes = new ArrayList<Long>();
     
            Object [] obj = cityList.getSelectedValues();
            Object source=e.getSource();
            if(source==addBtn)
            {
                right.setLayout(new GridLayout(obj.length,1));
                clockDisplay = new JPanel[obj.length];
                topRight.setLayout(new GridLayout(obj.length,1));
                ArrayList<String> cityNamesList = new ArrayList<String>();
                ArrayList<Long> cityTimes = new ArrayList<Long>();
                for(int i=0;i<obj.length;i++)
                {
                    String temp = (String)obj[i];
                    clockDisplay[i]=new JPanel();
                    cityName = temp.substring(0,temp.indexOf(","));
                    cityNamesList.add(cityName);
                    hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
                    currentTime = System.currentTimeMillis();
                    cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                    cityTimes.add(cityTime);
                    tick(cityTime);
                    clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                    time = new JLabel();
                    time.setOpaque(true);
                    timeInFormat = textAsTime(cityTime);
                    time.setText(timeInFormat);
                    clockDisplay[i].add(time);
                    topRight.add(clockDisplay[i]);
                }
                right.add(topRight);            
            }
        }
        public void setUpCities() 
        { 
           cities = new String []{"Accra,0","Addis Abada,+3","Adelaide,+11","Algiers,-1","Almaty,+6","Amman,+3","Amsterdam,+1","Anadyr,+12","Anchorage,-8","Ankara,+2","London,0","Paris,+1"};         
        } 
        public String textAsTime(long currentTime)  
        {  
            long second = (currentTime / 1000) % 60; 
            long minute = (currentTime / (1000 * 60)) % 60; 
            long hour = (currentTime / (1000 * 60 * 60)) % 24; 
            return String.format("%02d:%02d:%02d",hour,minute,second);  
        }
        public static void main(String [] args)
        {
            new AssignmentV1();
        }
        public long tick(long cityTime)
        {
            cityTime = cityTime+1000;
            return cityTime;
        }
    }


    --- Update ---

    on my original post, for point number 2 I have figured out how to remove all the previous information tha t was contained in the panel that the clocks were displayed in, removeAll();
    Last edited by digitalsystems; April 6th, 2014 at 01:40 PM. Reason: left out updated code

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    This is strange. Why use an array here:
         clockDisplay = new JPanel[1];

    The lists need to be created BEFORE the action listener method is called so the new times can be saved in it.

    Where is the list of labels to be updated? I only see one being updated:
            time.setText(timeInFormat);
    There needs to be a list of labels that is used in a loop to set the time for all of them.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    I was using it so that I could use the same reference to the array for when I had multiple selections.

    I have moved the creation of the lists to the constructor, I am thinking that I will also need a list of the strings that are going to be inserted into the labels, that way I can update them when I update the time of the selected cities, would this be correct?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    Create a class to hold all the data for a time display. Put instances of that class in a collection/list so it can be used to update the time and anything else about the display.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    sorry for not responding, thank you very much for your help.
    I have added another arraylist of JLabels that will hold all the jlabels as they are created in the for loop in the actionPerformed method.

    import java.awt.*;
    import java.util.ArrayList; 
    import javax.swing.*;  
    import java.awt.event.*;  
    import javax.swing.event.*;  
    import java.util.Date;  
    import java.text.SimpleDateFormat;  
     
    public class AssignmentV1 implements ActionListener/*,ListSelectionListener*/ 
    { 
        private String [] cities; 
        private JButton addBtn; 
        private JButton minusBtn; 
        private JList cityList; 
        private JPanel right; 
        private JPanel displayArea;
        private JPanel [] clockDisplay;
        private long currentTime;
        private long cityTime;
        private int hourDiff;
        private String cityName;
        private String timeInFormat;
        private JLabel time;
        private JPanel topRight;
        private ArrayList<String> cityNamesList;
        private ArrayList<Long> cityTimes;
        private ArrayList<JLabel> cityLabels;
        public AssignmentV1() 
        { 
            JFrame appWin = new JFrame("World Time");  
            appWin.setSize(400,400);  
            appWin.setLocationRelativeTo(null);  
            appWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     
            Font preferredFont = new Font("OCR A EXTENDED",Font.BOLD,50);  
     
            Container contentPane =appWin.getContentPane();  
     
            displayArea = new JPanel();  
            displayArea.setLayout(new GridLayout(1,2));  
     
            JPanel left = new JPanel();  
            left.setLayout(new GridLayout(2,1));  
     
            JPanel topLeft = new JPanel();  
            topLeft.setLayout(new FlowLayout(FlowLayout.CENTER));  
            //adding of +/- buttons to display 
            addBtn = new JButton();  
            addBtn.setText("+");  
            addBtn.addActionListener(this);  
            topLeft.add(addBtn);  
            minusBtn = new JButton();  
            minusBtn.setText("-");
            minusBtn.addActionListener(this);  
            topLeft.add(minusBtn);  
            left.add(topLeft);  
     
            //adding of list of cities to a scrollpane to add to display    
            JPanel bottomLeft=new JPanel(); 
     
            setUpCities(); 
            cityList=new JList(cities);    
            cityList.setSelectedIndex(0); 
            cityList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
            JScrollPane scrollableList = new JScrollPane(cityList);  
            bottomLeft.add(scrollableList);  
            left.add(bottomLeft);  
     
            right = new JPanel();
            topRight = new JPanel();
            clockDisplay = new JPanel[1];
            topRight.setLayout(new GridLayout(clockDisplay.length,1));
            for(int i=0;i<clockDisplay.length;i++)
            {
                clockDisplay[i]=new JPanel();
                cityName = cities[i].substring(0,cities[i].indexOf(","));
                hourDiff=Integer.parseInt(cities[i].substring(cities[i].indexOf(",")+1));
                currentTime = System.currentTimeMillis();
                cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                time = new JLabel();
                time.setOpaque(true);
                timeInFormat = textAsTime(cityTime);
                time.setText(timeInFormat);
     
                clockDisplay[i].add(time);
                topRight.add(clockDisplay[i]);
            }
            right.add(topRight);
     
     
            displayArea.add(left);  
            displayArea.add(right);  
            contentPane.add(displayArea);   
            Timer t= new Timer(1000,this);
            t.start();
            appWin.setVisible(true);
     
        } 
        public void actionPerformed(ActionEvent e)  
        {
            cityTime = cityTime+1000;
            timeInFormat=textAsTime(cityTime);
            time.setText(timeInFormat);
            cityNamesList = new ArrayList<String>();
            cityTimes = new ArrayList<Long>();
            cityLabels= new ArrayList<JLabel>();
     
            Object [] obj = cityList.getSelectedValues();
            Object source=e.getSource();
            if(source==addBtn)
            {
                topRight.removeAll();
                right.setLayout(new GridLayout(obj.length,1));
                clockDisplay = new JPanel[obj.length];
                topRight.setLayout(new GridLayout(obj.length,1));
                ArrayList<String> cityNamesList = new ArrayList<String>();
                ArrayList<Long> cityTimes = new ArrayList<Long>();
                for(int i=0;i<obj.length;i++)
                {
                    String temp = (String)obj[i];
                    clockDisplay[i]=new JPanel();
                    cityName = temp.substring(0,temp.indexOf(","));
                    cityNamesList.add(cityName);
                    hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
                    currentTime = System.currentTimeMillis();
                    cityTime = System.currentTimeMillis()+(1000*60*60*hourDiff);
                    cityTimes.add(cityTime);
                    clockDisplay[i].setBorder(BorderFactory.createTitledBorder(cityName));
                    time = new JLabel();
                    time.setOpaque(true);
                    timeInFormat = textAsTime(cityTime);
                    time.setText(timeInFormat);
                    cityLabels.add(time);
                    clockDisplay[i].add(time);
                    topRight.add(clockDisplay[i]);
                }
                right.add(topRight);            
            }
        }
        public void setUpCities() 
        { 
           cities = new String []{"Accra,0","Addis Abada,+3","Adelaide,+11","Algiers,-1","Almaty,+6","Amman,+3","Amsterdam,+1","Anadyr,+12","Anchorage,-8","Ankara,+2","London,0","Paris,+1"};         
        } 
        public String textAsTime(long currentTime)  
        {  
            long second = (currentTime / 1000) % 60; 
            long minute = (currentTime / (1000 * 60)) % 60; 
            long hour = (currentTime / (1000 * 60 * 60)) % 24; 
            return String.format("%02d:%02d:%02d",hour,minute,second);  
        }
        public static void main(String [] args)
        {
            new AssignmentV1();
        }
        //public long tick(long cityTime)
        //{
     
        //}
    }

    With regard to the class that you suggested in your previous post, I am not sure that I fully understand what you are suggesting. Is it to create a class that references the three array lists that I have created that contain the data associated with the time display? If it is I am not sure how to go about creating that. Could you give me some guidance on it?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    What are the 3 arraylists for? Could the data they contain be held in one class and instances of that class placed in a single arraylist?


    The posted code still is creating a new arraylist every time the actionPerformed() method is called, once a second. What happens to all those arraylists?
    Normally an arraylist is created one time in the constructor and then used in the methods of the class.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    thanks for your help with this question. I did not fully understand what you were suggesting so I went back to the professor for guidance and it turns out that many people were in the same question. I have since got a much clearer understanding of how to approach this question.

  16. #16
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Issues With Layout And Time Being Display

    Quote Originally Posted by digitalsystems View Post
    thanks for your help with this question. I did not fully understand what you were suggesting so I went back to the professor for guidance and it turns out that many people were in the same question. I have since got a much clearer understanding of how to approach this question.
    I think I have spoken too soon in saying that I have completed this. I have split the code into four different classes as per what my lecturer suggested.

    I have one remaining problem that I would be very grateful if anyone could give me guidance on.

    In the clockModel class, when I click on the "-" button (to remove a "clock" from the display) I am trying to see if the selected city is in the arraylist cityNames (created when in the addToDisplayMethod) and if it is to remove the associated jtextfield. I have got to the stage where I can check and see if the selected item is contained in the arraylist cityNames but I do not know how I can get at the associated jtextfield.

    Is it possible to check if the string that is the title of the jtextfield is the same as the text of the selected city? Or is there a different way that I should approch this?

    Thank you.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.util.*;
    public class ClockModel {
        private long timeInSeconds;
        private JList cityList; 
        ClockView view;
        private JPanel right;
        private ArrayList<Integer> hourDiffs;
        private ArrayList<String> cityNames;
        private JTextField worldClock[];
        private int hourDiff;
        private String cityName;
        public ClockModel(long startTimeInSeconds) {
            this.timeInSeconds = System.currentTimeMillis()/1000;
            view = new ClockView(this);
            this.cityList = view.cityList;
            this.right = view.right;
            this.hourDiffs = view.hourDiffs;
            this.cityNames = view.cityNames;
            this.worldClock = view.worldClock;
            this.hourDiff = view.hourDiff;
            this.cityName = view.cityName;
     
        }
        public ClockModel() {
            this(0);
        }
        public void tick() {
            timeInSeconds++;
            view.update(worldClock,hourDiffs);
        }
        public long currentTime() {
            return timeInSeconds;
        }
        public void addToDisplay()
        {
            Border lineBorder = BorderFactory.createLineBorder(Color.BLACK,1);
            Font font = new Font("Bradley Hand ITC", Font.BOLD, 24);
            view.right.removeAll();
            cityNames = new ArrayList<String>();
            hourDiffs = new ArrayList<Integer>();
            Object [] obj = view.cityList.getSelectedValues();
            worldClock = new JTextField[obj.length];
            for(int i=0;i<obj.length;i++)
            {
               String temp = (String)obj[i];
               cityName = temp.substring(0,temp.indexOf(","));
               hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
               worldClock[i]=new JTextField(8);
               worldClock[i].setFont(font);
               worldClock[i].setEditable(false);
               worldClock[i].setFocusable(false);
               worldClock[i].setBorder(BorderFactory.createTitledBorder(lineBorder,cityName));
               cityNames.add(cityName);
               right.add(worldClock[i]);
     
               hourDiffs.add(hourDiff);
            }
            view.update(worldClock,hourDiffs);   
        }  
        public void removeFromDisplay()
        {
            Object [] obj = view.cityList.getSelectedValues();
            //ArrayList<String> deleteList = new ArrayList<String>();
            for(int i=0;i<obj.length;i++)
            {
               String temp = (String)obj[i];
               cityName = temp.substring(0,temp.indexOf(","));
               hourDiff=Integer.parseInt(temp.substring(temp.indexOf(",")+1));
               if(cityNames.contains(cityName))
               {
                  //deleteList.add(cityName);
                  //right.remove(worldClock[i]);
               }
            }
        }
    }

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.util.*;
     
     
    public class ClockView {
        JTextField worldClock[];
        private ClockModel model;
        JList cityList;
        JPanel right;
        private String [] cities;
        ArrayList<Integer> hourDiffs;
        ArrayList<String> cityNames;
        int hourDiff;
        String cityName;
        AddRemoveButton addBtn;
        AddRemoveButton minusBtn;
        public ClockView(ClockModel model) {
            JFrame clockFace = new JFrame("World Clock");
            clockFace.setSize(600,600);
            clockFace.setLocationRelativeTo(null);
            clockFace.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            Container contentPane = clockFace.getContentPane();
     
            JPanel displayArea = new JPanel(new GridLayout(1,2));
     
            JPanel left = new JPanel(new GridLayout(2,1));
            JPanel topLeft = new JPanel(new FlowLayout());
     
            AddRemoveButton addBtn = new AddRemoveButton("+",model);
            topLeft.add(addBtn);
            AddRemoveButton minusBtn = new AddRemoveButton("-",model);
            topLeft.add(minusBtn);
            left.add(topLeft);
     
     
            JPanel bottomLeft = new JPanel();
            setUpCities();
            cityList=new JList(cities);
            int selectedIndex = 3;
            cityList.setSelectedIndex(selectedIndex);
            cityList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            int currentIndex=cityList.getSelectedIndex();
            JScrollPane scrollableList = new JScrollPane(cityList); 
            bottomLeft.add(scrollableList); 
            left.add(bottomLeft);
     
            right = new JPanel(new FlowLayout());
     
            Border lineBorder = BorderFactory.createLineBorder(Color.BLACK,1);
            Font font = new Font("Bradley Hand ITC", Font.BOLD, 24);
     
            worldClock = new JTextField[1];
            worldClock[0]=new JTextField(8);
            worldClock[0].setFont(font);
            worldClock[0].setEditable(false);
            worldClock[0].setFocusable(false);
            worldClock[0].setHorizontalAlignment(JTextField.CENTER);
            cityName = cities[selectedIndex].substring(0,cities[selectedIndex].indexOf(","));
            cityNames = new ArrayList<String>();
            cityNames.add(cityName);
            worldClock[0].setBorder(BorderFactory.createTitledBorder(lineBorder,cityName));
            right.add(worldClock[0]);
            hourDiff=Integer.parseInt(cities[selectedIndex].substring(cities[selectedIndex].indexOf(",")+1));
            hourDiffs = new ArrayList<Integer>();
            hourDiffs.add(hourDiff);
     
            displayArea.add(left);
            displayArea.add(right);
            contentPane.add(displayArea);
     
            this.model = model;
            new ClockController(model);
     
            update(worldClock,hourDiffs);
            clockFace.setVisible(true);
        }
     
        public void update(JTextField [] worldClock, ArrayList<Integer> hourDiffs) 
        {
            for(int i=0;i<worldClock.length;i++)
            {
                worldClock[i].setText(secondsAsTimeText(model.currentTime()+((hourDiffs.get(i))*60*60)));
            }
        }
     
        public String secondsAsTimeText(long timeInSeconds) {
            long hours, minutes, seconds ;
            minutes = timeInSeconds / 60;
            seconds = timeInSeconds % 60;
            hours = minutes / 60;
            hours = hours%24;
            minutes = minutes % 60;
            return String.format("%02d:%02d:%02d",hours,minutes,seconds);
        }
        public void setUpCities()
        {
           cities = new String []{"Accra,0","Addis Abada,+3","Adelaide,+11","Algiers,-1","Almaty,+6","Amman,+3","Amsterdam,+1","Anadyr,+12","Anchorage,-8","Ankara,+2","London,0","Paris,+1"};        
        }
    }

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
     
    public class ClockController implements ActionListener {
        private ClockModel model;
     
        public ClockController(ClockModel model)
        {
            this.model = model;
            Timer timer = new Timer(1000,this);
            timer.start();
        }
     
        public void actionPerformed(ActionEvent event)
        {
            model.tick();
        }
    }

    import javax.swing.*;
    import java.awt.event.*;
    public class AddRemoveButton extends JButton implements ActionListener
    {
        private ClockModel model;
        private ClockView view;
        private String buttonText;
        //private AddRemoveButton addBtn;
        //private AddRemoveButton minusBtn;
        public AddRemoveButton(String buttonText, ClockModel model)
        {
            super(buttonText);
            addActionListener(this);
            this.model=model;
            this.buttonText = buttonText;
            //this.addBtn = view.addBtn;
            //this.minusBtn = view.minusBtn;
        }
        public void actionPerformed(ActionEvent e)
        {
            Object source = e.getSource();
            if(buttonText=="+")
            {
                model.addToDisplay();
            }
            else
            model.removeFromDisplay();
        }
    }

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Issues With Layout And Time Being Display

    how I can get at the associated jtextfield.
    By defining ONE class that has references to ALL the parts and data needed to display the clock.
    One of the fields in the class would be a reference to the text field.
    Having the data in separate lists makes for difficult processing.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. GPA- Need to display having issues
    By ladydre in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 11th, 2013, 11:25 PM
  2. How to display data and time in JTable
    By kpat in forum AWT / Java Swing
    Replies: 2
    Last Post: April 8th, 2012, 12:19 PM
  3. Replies: 0
    Last Post: April 3rd, 2012, 08:57 AM
  4. How do I display 4 items at a time of an ArrayList?
    By JavaStruggler in forum Member Introductions
    Replies: 5
    Last Post: August 9th, 2011, 02:33 PM
  5. display time
    By kalees in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: January 1st, 2010, 07:40 AM