Results 1 to 20 of 20
  1. #1
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default Putting JLabels into a JScrollpane

    EDIT:
    This is no longer the problem, and it should not be necessary to read the entire topic if that's what scares people from answering.
    Go to post 9 (direct link here (which sadly opens in a new window)) to see the new problem (scrolling to specific position), with the entire code and image illustrations of the desired achievements.


    ORIGINAL MESSAGE:
    Now, the project that I'm currently doing is a cell-phone simulation (of one of the good old non-smartphones - something like Nokia 3310i).
    The reason I need labels in my JScrollpane is simply because the code we've been given only lets us type text into either JLabels (when using the buttons on the phone).

    And basically this problem I'm dealing with at the moment is displaying a list of things to type in when creating or editing a contact.
    It should contain a label for given name, surname, cellphone number, landline number and work number - and a header for each of those labels.

    Now since I also need to disable all Mouse- and MouseMotionListeners, I figured I could get around it by manually scrolling to a certain point when jumping between which labels to write text in.

    Now, I can tell you that the only experience I have with JScrollpanes are that you can just add a JList or JTable to it and it works automatically.
    Then I know how to set the bar-policies (when the vertical or horizontal bars should be shown) and then I read a few things about setting viewports which I think this problem is about.

    Now I'm sorry for writing this huge wall of text but I would just like to prepare my saviour (in the form of one of you guys, providing a much-appreciated answers) how to explain this as short and easy as possible so it doesn't take too much of his/her time either.

    Now, even though I think showing code might be irrelevant in this case, I'm still showing something just to get you into the pattern I'm coding in:
    Java Code:
    import java.awt.Color;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingConstants;
    
    public class MainFrame extends JFrame{
        
        private JPanel pnlCreateContactDisplay;
        private JLabel lblCreateContactGivenName, lblCreateContactSurname, lblCreateContactCellNo,
            lblCreateContactLandlineNo, lblCreateContactWorkNo;
        private JLabel lblCreateContactGivenNameHeader, lblCreateContactSurnameHeader,
            lblCreateContactCellNoHeader, lblCreateContactLandlineNoHeader, lblCreateContactWorkNoHeader;
        
        public MainFrame() {
            
            this.setTitle("MOKIU v0.1212 BETA");
            this.setSize(315, 730);
            this.setLocation(500, 5);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(null);
            this.getContentPane().setBackground(Color.DARK_GRAY);
            this.setResizable(false);
    
            pnlCreateContactDisplay = new JPanel();    
            pnlCreateContactDisplay.setSize(255, 270);
            pnlCreateContactDisplay.setLocation(25, 25);
            pnlCreateContactDisplay.setLayout(null);
            this.add(pnlCreateContactDisplay);
            pnlCreateContactDisplay.setBackground(Color.WHITE);
            
            lblCreateContactGivenNameHeader = new JLabel("Fornavn:");
            pnlCreateContactDisplay.add(lblCreateContactGivenNameHeader);
            lblCreateContactGivenNameHeader.setSize(160,20);
            lblCreateContactGivenNameHeader.setLocation(30, 30);
            lblCreateContactGivenNameHeader.setForeground(Color.WHITE);
            lblCreateContactGivenNameHeader.setOpaque(true);
            
            lblCreateContactGivenName = new JLabel();
            pnlCreateContactDisplay.add(lblCreateContactGivenName);
            lblCreateContactGivenName.setSize(150,20);
            lblCreateContactGivenName.setLocation(35, 55);
            lblCreateContactGivenName.setVerticalAlignment(SwingConstants.TOP);
            lblCreateContactGivenName.setForeground(Color.BLACK);
            lblCreateContactGivenName.setOpaque(true);
            
            lblCreateContactSurnameHeader = new JLabel("Efternavn:");
            pnlCreateContactDisplay.add(lblCreateContactSurnameHeader);
            lblCreateContactSurnameHeader.setSize(160,20);
            lblCreateContactSurnameHeader.setLocation(30, 90);
            lblCreateContactSurnameHeader.setForeground(Color.WHITE);
            lblCreateContactSurnameHeader.setOpaque(true);
            
            lblCreateContactSurname = new JLabel();
            pnlCreateContactDisplay.add(lblCreateContactSurname);
            lblCreateContactSurname.setSize(150,20);
            lblCreateContactSurname.setLocation(35, 115);
            lblCreateContactSurname.setVerticalAlignment(SwingConstants.TOP);
            lblCreateContactSurname.setForeground(Color.BLACK);
            lblCreateContactSurname.setOpaque(true);
            
            lblCreateContactCellNoHeader = new JLabel("Mobilnummer:");
            pnlCreateContactDisplay.add(lblCreateContactCellNoHeader);
            lblCreateContactCellNoHeader.setSize(160,20);
            lblCreateContactCellNoHeader.setLocation(30, 150);
            lblCreateContactCellNoHeader.setForeground(Color.WHITE);
            lblCreateContactCellNoHeader.setOpaque(true);
            
            lblCreateContactCellNo = new JLabel();
            pnlCreateContactDisplay.add(lblCreateContactCellNo);
            lblCreateContactCellNo.setSize(150,20);
            lblCreateContactCellNo.setLocation(35, 175);
            lblCreateContactCellNo.setVerticalAlignment(SwingConstants.TOP);
            lblCreateContactCellNo.setForeground(Color.BLACK);
            lblCreateContactCellNo.setOpaque(true);
            
            lblCreateContactLandlineNoHeader = new JLabel("Fastnet-nummer:");
            pnlCreateContactDisplay.add(lblCreateContactLandlineNoHeader);
            lblCreateContactLandlineNoHeader.setSize(160,20);
            lblCreateContactLandlineNoHeader.setLocation(30, 210);
            lblCreateContactLandlineNoHeader.setForeground(Color.WHITE);
            lblCreateContactLandlineNoHeader.setOpaque(true);
            
            lblCreateContactLandlineNo = new JLabel();
            pnlCreateContactDisplay.add(lblCreateContactLandlineNo);
            lblCreateContactLandlineNo.setSize(150,20);
            lblCreateContactLandlineNo.setLocation(35, 235);
            lblCreateContactLandlineNo.setVerticalAlignment(SwingConstants.TOP);
            lblCreateContactLandlineNo.setForeground(Color.BLACK);
            lblCreateContactLandlineNo.setOpaque(true);
            
            lblCreateContactWorkNoHeader = new JLabel("Arbejdsnummer:");
            pnlCreateContactDisplay.add(lblCreateContactWorkNoHeader);
            lblCreateContactWorkNoHeader.setSize(160,20);
            lblCreateContactWorkNoHeader.setLocation(30, 270);
            lblCreateContactWorkNoHeader.setForeground(Color.WHITE);
            lblCreateContactWorkNoHeader.setOpaque(true);
            
            lblCreateContactWorkNo = new JLabel();
            pnlCreateContactDisplay.add(lblCreateContactWorkNo);
            lblCreateContactWorkNo.setSize(150,20);
            lblCreateContactWorkNo.setLocation(35, 295);
            lblCreateContactWorkNo.setVerticalAlignment(SwingConstants.TOP);
            lblCreateContactWorkNo.setForeground(Color.BLACK);
            lblCreateContactWorkNo.setOpaque(true);
            
            //FROM HERE
            JScrollPane createContactScrollPane = new JScrollPane();
            createContactScrollPane.add(lblCreateContactGivenNameHeader);
            createContactScrollPane.add(lblCreateContactGivenName);
            createContactScrollPane.add(lblCreateContactSurnameHeader);
            createContactScrollPane.add(lblCreateContactSurname);
            createContactScrollPane.add(lblCreateContactCellNoHeader);
            createContactScrollPane.add(lblCreateContactCellNo);
            createContactScrollPane.add(lblCreateContactLandlineNoHeader);
            createContactScrollPane.add(lblCreateContactLandlineNo);
            createContactScrollPane.add(lblCreateContactWorkNoHeader);
            createContactScrollPane.add(lblCreateContactWorkNo);
            createContactScrollPane.setSize(205, 220);
            createContactScrollPane.setLocation(25, 25);
            createContactScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            pnlCreateContactDisplay.add(createContactScrollPane);
            //TO HERE
            
            this.setVisible(true);
        }
    }
    I've tested the code and it gives the same graphical error, although I have an ImageIcon background instead of just a white colour.

    Now, if you comment out from "//FROM HERE" to "//TO HERE", it'll work perfectly except landlineNo, workNo - and their headers - are out of the JPanel screen.

    If the request for what exactly I need done isn't specific enough I'll make a quick punctual list:
    • Make it possible to, by clicking a button, scroll down to a label that isn't visible.
    • Make the Scrollpane background transparent - and remove the borders.
    • A smaller priority is actually showing the bars and knobs since they'll only be there for visually guiding if you're in the bottom or in the top. (And by this I mean I'll be removing all mouse actions from the scrollpane.)


    Thank you very much in advance.

    EDIT: I tried adding all labels to a JPanel and then adding that JPanel to the JScrollpane but still no success.
    Last edited by Muskar; 12-13-2010 at 03:36 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Muskar View Post
    Now, if you comment out from "//FROM HERE" to "//TO HERE", it'll work perfectly except landlineNo, workNo - and their headers - are out of the JPanel screen.
    I don't see those comments. Am I overlooking them?


    EDIT: I tried adding all labels to a JPanel and then adding that JPanel to the JScrollpane but still no success.
    You may need to show us that code.

    Luck


    edit: You're adding a bunch of chit to the JScrollPane itself, and that just won't work. You need to add a single JPanel (or other JComponent) to the JScrollPane's JViewport (which you can get by calling getViewport() on the JScrollPane or also another way to do this is to construct the JScrollPane with the viewing panel passed as a parameter) for you to be able to scroll anything. With all that null layout going on, you may need to have your JPanel implement Scrollable.
    Last edited by Fubarable; 12-12-2010 at 05:30 PM.

  3. #3
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    I don't see those comments. Am I overlooking them?
    Sorry, I must have copied the text just before I wrote that - I added it now - although I don't think it's very important information.

    Quote Originally Posted by Fubarable View Post
    You may need to show us that code.
    I think I have to use a JPanel anyway since I would prefer giving it a background ImageIcon - so I'll show you the new code in a second.

    Quote Originally Posted by Fubarable View Post
    You're adding a bunch of chit to the JScrollPane itself, and that just won't work. You need to add a single JPanel (or other JComponent) to the JScrollPane's JViewport (which you can get by calling getViewport() on the JScrollPane or also another way to do this is to construct the JScrollPane with the viewing panel passed as a parameter) for you to be able to scroll anything. With all that null layout going on, you may need to have your JPanel implement Scrollable.
    Alright, I'll try all your suggestions out and pass the new code if it won't work, thanks a lot.
    EDIT: I've been reading around the web and understand that using a null layout gives a problem - but I have no idea where to begin writing whatever should be in the implemented methods of JPanel that implements Scrollable, also because of the fact that a JPanel is Scrollable already. So could you give me a hint? Values I can play around with myself but I'm not familiar with implements Scrollable in the first place - and my Google-skills didn't give me any examples that weren't messy or slightly irrelevant to my case.

    As far as that goes, I've understood that I need to make it return another preferred size than (0,0) - which is, as far as Google-sources tell, null-layout's preferred size - but it doesn't seem like it works all the magic for it to work.

    I'll be posting the code in a few minutes when I've written it.

    EDIT2:
    Here goes:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingConstants;
    
    public class MainFrame extends JFrame{
        
        private JPanel pnlCreateContactDisplay;
        private JPanel pnlCreateContactScrollable;
        private JLabel lblCreateContactGivenName, lblCreateContactSurname, lblCreateContactCellNo,
            lblCreateContactLandlineNo, lblCreateContactWorkNo;
        private JLabel lblCreateContactGivenNameHeader, lblCreateContactSurnameHeader,
            lblCreateContactCellNoHeader, lblCreateContactLandlineNoHeader, lblCreateContactWorkNoHeader;
        
        public MainFrame() {
            
            this.setTitle("MOKIU v0.1211 BETA");
            this.setSize(315, 730);
            this.setLocation(500, 5);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(null);
    
            pnlCreateContactDisplay = new JPanel();    
            pnlCreateContactDisplay.setSize(255, 270);
            pnlCreateContactDisplay.setLocation(25, 25);
            pnlCreateContactDisplay.setLayout(null);
            this.add(pnlCreateContactDisplay);
            
            [COLOR="Red"]pnlCreateContactScrollable.setPreferredSize(new Dimension(255,270));[/COLOR]
            pnlCreateContactScrollable.setSize(255, 270);
            pnlCreateContactScrollable.setLocation(10, 25);
            pnlCreateContactScrollable.setLayout(null);
            pnlCreateContactDisplay.add(pnlCreateContactScrollable);
            
            lblCreateContactGivenNameHeader = new JLabel("Fornavn:");
            pnlCreateContactScrollable.add(lblCreateContactGivenNameHeader);
            lblCreateContactGivenNameHeader.setSize(160,20);
            lblCreateContactGivenNameHeader.setLocation(5, 5);
            
            lblCreateContactGivenName = new JLabel();
            pnlCreateContactScrollable.add(lblCreateContactGivenName);
            lblCreateContactGivenName.setSize(150,20);
            lblCreateContactGivenName.setLocation(10, 35);
            
            lblCreateContactSurnameHeader = new JLabel("Efternavn:");
            pnlCreateContactScrollable.add(lblCreateContactSurnameHeader);
            lblCreateContactSurnameHeader.setSize(160,20);
            lblCreateContactSurnameHeader.setLocation(5, 65);
            
            lblCreateContactSurname = new JLabel();
            pnlCreateContactScrollable.add(lblCreateContactSurname);
            lblCreateContactSurname.setSize(150,20);
            lblCreateContactSurname.setLocation(10, 90);
            
            lblCreateContactCellNoHeader = new JLabel("Mobilnummer:");
            pnlCreateContactScrollable.add(lblCreateContactCellNoHeader);
            lblCreateContactCellNoHeader.setSize(160,20);
            lblCreateContactCellNoHeader.setLocation(2, 125);
            
            lblCreateContactCellNo = new JLabel();
            pnlCreateContactScrollable.add(lblCreateContactCellNo);
            lblCreateContactCellNo.setSize(150,20);
            lblCreateContactCellNo.setLocation(10, 150);
            
            lblCreateContactLandlineNoHeader = new JLabel("Fastnet-nummer:");
            pnlCreateContactScrollable.add(lblCreateContactLandlineNoHeader);
            lblCreateContactLandlineNoHeader.setSize(160,20);
            lblCreateContactLandlineNoHeader.setLocation(2, 195);
            
            lblCreateContactLandlineNo = new JLabel();
            pnlCreateContactScrollable.add(lblCreateContactLandlineNo);
            lblCreateContactLandlineNo.setSize(150,20);
            lblCreateContactLandlineNo.setLocation(10, 210);
            
            lblCreateContactWorkNoHeader = new JLabel("Arbejdsnummer:");
            pnlCreateContactScrollable.add(lblCreateContactWorkNoHeader);
            lblCreateContactWorkNoHeader.setSize(160,20);
            lblCreateContactWorkNoHeader.setLocation(5, 245);
            
            lblCreateContactWorkNo = new JLabel();
            pnlCreateContactScrollable.add(lblCreateContactWorkNo);
            lblCreateContactWorkNo.setSize(150,20);
            lblCreateContactWorkNo.setLocation(10, 270);
            
            
            JScrollPane createContactScrollPane = new JScrollPane();
            createContactScrollPane.add(pnlCreateContactScrollable);
            createContactScrollPane.setSize(205, 220);
            createContactScrollPane.setLocation(25, 25);
            pnlCreateContactDisplay.add(createContactScrollPane);
            
            this.setVisible(true);
        }
    }

    This code gives a nullpointer exception in the line marked with red which I have no clue why it gives me.

    EDIT 3:
    I'm assuming you don't want to test the looks of it yourself, so I just removed most of the irrelevant lines of the above text.
    Last edited by Muskar; 12-12-2010 at 08:00 PM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    At the line where the NPE occurs you're trying to call a method on an object (the JPanel) that has not been constructed. Search your code for this variable and check for yourself if you ever construct it (create a new JPanel).

  5. #5
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    At the line where the NPE occurs you're trying to call a method on an object (the JPanel) that has not been constructed. Search your code for this variable and check for yourself if you ever construct it (create a new JPanel).
    Right, sorry, added the following line above the red line, in case other people are reading this:
    Java Code:
    pnlCreateContactScrollable = new JPanel();
    That, of course, solved the exception. But on to the problem:

    It's still not working although it seems like the JScrollpane is on top of the panel instead of the other way around.

    So since I have no idea where to begin solving this, I think we're going towards trying to implement Scrollable - now, any suggestions what I might write?

    In case you don't remember - and therefore would have to research it; I'll spare you:
    Java Code:
    public Dimension getPreferredScrollableViewportSize() {
        return null;
    }
    
    public int getScrollableBlockIncrement(Rectangle arg0, int arg1, int arg2) {
        return 0;
    }
    
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
    
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }
    
    public int getScrollableUnitIncrement(Rectangle arg0, int arg1, int arg2) {
        return 0;
    }

    EDIT:
    Alright, I fixed making the JPanel visible by adding the following line:
    Java Code:
    createContactScrollPane.setViewportView(pnlCreateContactScrollable);
    And in edition I think the reason that I can't scroll yet is because I need to make the panel, with my labels in, to the entire size of where the labels are and of course also the setPreferredSize Dimension.
    I'll return to tell you if it works.

    EDIT2:
    It works.
    The code changed was this:
    Java Code:
    //FROM
    pnlCreateContactScrollable.setPreferredSize(new Dimension(255,270));
    pnlCreateContactScrollable.setSize(255, 270);
    
    //TO
    pnlCreateContactScrollable.setPreferredSize(new Dimension(255,295));
    pnlCreateContactScrollable.setSize(255, 295);
    Now what I need to do is set the viewport to a certain place when clicking a button.
    Last edited by Muskar; 12-12-2010 at 08:32 PM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Muskar View Post
    Now what I need to do is set the viewport to a certain place when clicking a button.
    If you have further problems, you may wish to repost the latest code and give some details on the new problem. Glad you've got some of it working though.

  7. #7
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    If you have further problems, you may wish to repost the latest code and give some details on the new problem. Glad you've got some of it working though.
    The problem itself has no code (except for what has already been provided). The problem is to figure out how to set the viewport (which is, as far as I understand, what is viewable on the screen in the scrollpane) to somewhere else than the default location for the component.

    Now I don't know if I should try calling some methods to scroll the bar a certain amount of pixels or try to manually change the viewport to a specific location or something third.

    The following code was tried without success (the entire JPanel disappears):
    Java Code:
    JViewport test = new JViewport();
    test.toViewCoordinates(new Dimension(0,20));
    createContactScrollPane.setViewport(test);
    EDIT:
    Trying to use a "Point" to set the location was the second try (the JPanel shows - but is not scrolled to anywhere - and yes, I tried changing the point's values):
    Java Code:
    createContactScrollPane.setViewportView(pnlCreateContactScrollable);
    Point testPoint = createContactScrollPane.getViewport().getViewPosition();
    //I system.out.print'ed the X and Y values of testPoint: X = -10.0 & Y = -25.0
    testPoint.setLocation(-10, 25);
    JViewport testViewPort = new JViewport();
    testViewPort.setView(pnlCreateContactScrollable);
    testViewPort.toViewCoordinates(testPoint);
    createContactScrollPane.setViewport(testViewPort);
    Last edited by Muskar; 12-12-2010 at 09:08 PM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Muskar View Post
    The problem itself has no code (except for what has already been provided).
    Yes, but you've made lots of changes to the code incrementally. Best to post its final incarnation below and also a picture of what you're trying to achieve or a much more detailed description.

  9. #9
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Yes, but you've made lots of changes to the code incrementally. Best to post its final incarnation below and also a picture of what you're trying to achieve or a much more detailed description.
    Regarding the changes, I don't think they're that big but for your viewing pleasure I'll provide it anyway:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingConstants;
    
    public class MainFrame extends JFrame{
        
        private JPanel pnlCreateContactDisplay;
        private JPanel pnlCreateContactScrollable;
        private JLabel lblCreateContactGivenName, lblCreateContactSurname, lblCreateContactCellNo,
            lblCreateContactLandlineNo, lblCreateContactWorkNo;
        private JLabel lblCreateContactGivenNameHeader, lblCreateContactSurnameHeader,
            lblCreateContactCellNoHeader, lblCreateContactLandlineNoHeader, lblCreateContactWorkNoHeader;
        
        public MainFrame() {
            
            this.setTitle("MOKIU v0.1211 BETA");
            this.setSize(315, 730);
            this.setLocation(500, 5);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(null);
    
            pnlCreateContactDisplay = new JPanel();    
            pnlCreateContactDisplay.setSize(255, 270);
            pnlCreateContactDisplay.setLocation(25, 25);
            pnlCreateContactDisplay.setLayout(null);
            this.add(pnlCreateContactDisplay);
            
            pnlCreateContactScrollable.setPreferredSize(new Dimension(255,305)); 
    		pnlCreateContactScrollable.setSize(255, 305);
    		pnlCreateContactScrollable.setLocation(10, 25);
            pnlCreateContactScrollable.setLayout(null);
            pnlCreateContactDisplay.add(pnlCreateContactScrollable);
            
            lblCreateContactGivenNameHeader = new JLabel("Fornavn:");
    		pnlCreateContactScrollable.add(lblCreateContactGivenNameHeader);
    		lblCreateContactGivenNameHeader.setSize(160,20);
    		lblCreateContactGivenNameHeader.setLocation(15, 15);
    		lblCreateContactGivenNameHeader.setForeground(Color.WHITE);
    		lblCreateContactGivenNameHeader.setOpaque(true);
    		
    		lblCreateContactGivenName = new JLabel();
    		pnlCreateContactScrollable.add(lblCreateContactGivenName);
    		lblCreateContactGivenName.setSize(150,20);
    		lblCreateContactGivenName.setLocation(20, 45);
    		lblCreateContactGivenName.setVerticalAlignment(SwingConstants.TOP);
    		lblCreateContactGivenName.setForeground(Color.BLACK);
    		lblCreateContactGivenName.setOpaque(true);
    		
    		lblCreateContactSurnameHeader = new JLabel("Efternavn:");
    		pnlCreateContactScrollable.add(lblCreateContactSurnameHeader);
    		lblCreateContactSurnameHeader.setSize(160,20);
    		lblCreateContactSurnameHeader.setLocation(15, 75);
    		lblCreateContactSurnameHeader.setForeground(Color.WHITE);
    		lblCreateContactSurnameHeader.setOpaque(true);
    		
    		lblCreateContactSurname = new JLabel();
    		pnlCreateContactScrollable.add(lblCreateContactSurname);
    		lblCreateContactSurname.setSize(150,20);
    		lblCreateContactSurname.setLocation(20, 100);
    		lblCreateContactSurname.setVerticalAlignment(SwingConstants.TOP);
    		lblCreateContactSurname.setForeground(Color.BLACK);
    		lblCreateContactSurname.setOpaque(true);
    		
    		lblCreateContactCellNoHeader = new JLabel("Mobilnummer:");
    		pnlCreateContactScrollable.add(lblCreateContactCellNoHeader);
    		lblCreateContactCellNoHeader.setSize(160,20);
    		lblCreateContactCellNoHeader.setLocation(15, 135);
    		lblCreateContactCellNoHeader.setForeground(Color.WHITE);
    		lblCreateContactCellNoHeader.setOpaque(true);
    		
    		lblCreateContactCellNo = new JLabel();
    		pnlCreateContactScrollable.add(lblCreateContactCellNo);
    		lblCreateContactCellNo.setSize(150,20);
    		lblCreateContactCellNo.setLocation(20, 160);
    		lblCreateContactCellNo.setVerticalAlignment(SwingConstants.TOP);
    		lblCreateContactCellNo.setForeground(Color.BLACK);
    		lblCreateContactCellNo.setOpaque(true);
    		
    		lblCreateContactLandlineNoHeader = new JLabel("Fastnet-nummer:");
    		pnlCreateContactScrollable.add(lblCreateContactLandlineNoHeader);
    		lblCreateContactLandlineNoHeader.setSize(160,20);
    		lblCreateContactLandlineNoHeader.setLocation(15, 195);
    		lblCreateContactLandlineNoHeader.setForeground(Color.WHITE);
    		lblCreateContactLandlineNoHeader.setOpaque(true);
    		
    		lblCreateContactLandlineNo = new JLabel();
    		pnlCreateContactScrollable.add(lblCreateContactLandlineNo);
    		lblCreateContactLandlineNo.setSize(150,20);
    		lblCreateContactLandlineNo.setLocation(20, 220);
    		lblCreateContactLandlineNo.setVerticalAlignment(SwingConstants.TOP);
    		lblCreateContactLandlineNo.setForeground(Color.BLACK);
    		lblCreateContactLandlineNo.setOpaque(true);
    		
    		lblCreateContactWorkNoHeader = new JLabel("Arbejdsnummer:");
    		pnlCreateContactScrollable.add(lblCreateContactWorkNoHeader);
    		lblCreateContactWorkNoHeader.setSize(160,20);
    		lblCreateContactWorkNoHeader.setLocation(15, 255);
    		lblCreateContactWorkNoHeader.setForeground(Color.WHITE);
    		lblCreateContactWorkNoHeader.setOpaque(true);
    		
    		lblCreateContactWorkNo = new JLabel();
    		pnlCreateContactScrollable.add(lblCreateContactWorkNo);
    		lblCreateContactWorkNo.setSize(150,20);
    		lblCreateContactWorkNo.setLocation(20, 280);
    		lblCreateContactWorkNo.setVerticalAlignment(SwingConstants.TOP);
    		lblCreateContactWorkNo.setForeground(Color.BLACK);
    		lblCreateContactWorkNo.setOpaque(true);
    		
    		JScrollPane createContactScrollPane = new JScrollPane();
    		createContactScrollPane.add(pnlCreateContactScrollable);
    		createContactScrollPane.setSize(205, 220);
    		createContactScrollPane.setLocation(25, 25);
    		createContactScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    		pnlCreateContactDisplay.add(createContactScrollPane);
    		createContactScrollPane.setViewportView(pnlCreateContactScrollable);
            
            this.setVisible(true);
        }
    }


    The following image is two instances of the program itself - I'm trying to scroll from the image on the left to the image on the right - without using the mouse scroll it:
    Last edited by Muskar; 12-12-2010 at 09:35 PM.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    So you're entering text into JLabels not JTextFields? How are you moving from one line to the next? Tab? How are you detecting button pushes or key strokes? Mouse listener? key listener? key binding? action listener?

  11. #11
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    So you're entering text into JLabels not JTextFields? How are you moving from one line to the next? Tab? How are you detecting button pushes or key strokes? Mouse listener? key listener? key binding? action listener?
    Yes, I'm entering text to labels, since we got provided the so-called "InputKeysPanel" that handles the number-key buttons and the timer etc. when pressing a button to change the char.
    - And regarding the current looks, they will change after this function has been implemented, since I'll be replacing the test-background (black with red border) with a background that makes it look a bit more like textfields but a little more fancy.

    The buttons you see with the "2 abc" etc. are JButtons but with a black background instead - and they listen only to mouse clicks.

    Jumping between labels is whenever you've reached the end the text you've written with the "cursor" (underline - and yes, the text is html-formatted) and you press on the down arrow button (which also navigates to the right, in text) you jump to the next label and so on.


    Although I need no help with where to place my code when I have it (and it would be hard for others to 'quickly do' since my MainFrame class is 1700 lines and counting), I only need help to perform the act in the first place.

    EDIT:
    Since I just explained how the jumping works I could also tell you that what I want to do is to scroll whenever I hit a label outside of the screen - to around 5 pixels lower than label's area itself (and of course the other way around for scrolling up but that's irrelevant since it'd be easy to do whenever I figure out how to scroll-by-code anyway).
    Last edited by Muskar; 12-12-2010 at 10:22 PM.

  12. #12
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    It's without the intention of stressing anyone by the fact that I have to hand-in this project in 5 hours (it's 3 am here) but since that is in fact the truth, I'm now bumping this message - also because of the fact that I think that potential helpers might have been scared of the enormous size of the question - so I decided to add an introductory text to tell them that they didn't have to read through that big pile of text.

    Thank you very much for your time!

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    To get a JScrollPane to scroll to a certain position, you can call scrollRectToVisible on the component held by the JScrollPane's JViewport. I've used this when for instance my scroll pane holds a lot of JTextFields and I want the field with the focus to be in view. For an example of this that uses JTextFields that have a focus listener added, please take a look below:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class MainFrameB extends JPanel {
       private static final String[] LABELS = {"One", "Two", "Three", "Four", "Five", "Six", 
          "Seven", "Eight", "Nine", "Ten"};
       private static final int MAIN_WIDTH = 315;
       private static final int MAIN_HEIGHT = 700;
       private static final int GAP = 45;
       private static final Component PLACE_HOLDER = Box.createVerticalStrut(380);
       private JPanel displayPanel = new JPanel();
       private JScrollPane displayScrollPane = new JScrollPane(displayPanel, 
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
       private JTextField[] fields = new JTextField[LABELS.length];
    
       public MainFrameB() {
          displayPanel.setLayout(new GridBagLayout());
          int dpGap = 5;
          displayPanel.setBorder(BorderFactory.createEmptyBorder(dpGap , dpGap, dpGap, dpGap));
          for (int i = 0; i < LABELS.length; i++) {
             fields[i] = new JTextField(10);
             fields[i].addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                   fieldFocusGained(e);
                }
             });
             displayPanel.add(new JLabel(LABELS[i] + ":"), getGbc(0, i));
             displayPanel.add(fields[i], getGbc(1, i));
          }
          
          setPreferredSize(new Dimension(MAIN_WIDTH, MAIN_HEIGHT));
          setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
          setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
          add(displayScrollPane);
          
          add(PLACE_HOLDER); // delete later
       }
    
       private void fieldFocusGained(FocusEvent e) {
          JTextField field = (JTextField)e.getSource();
          Rectangle rect = field.getBounds();
          displayPanel.scrollRectToVisible(new Rectangle(0, 0, 10, 10)); // to go to very top
          displayPanel.scrollRectToVisible(rect);
       }
    
       private GridBagConstraints getGbc(int gridX, int gridY) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = gridX;
          gbc.gridy = gridY;
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          gbc.anchor = (gridX == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
          gbc.fill = (gridX == 0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;
          gbc.insets = new Insets(10, 5, 10, 5);
          return gbc;
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("MainFrameB");
          frame.getContentPane().add(new MainFrameB());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  14. #14
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    To get a JScrollPane to scroll to a certain position, you can call scrollRectToVisible on the component held by the JScrollPane's JViewport. I've used this when for instance my scroll pane holds a lot of JTextFields and I want the field with the focus to be in view. For an example of this that uses JTextFields that have a focus listener added, please take a look below:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class MainFrameB extends JPanel {
       private static final String[] LABELS = {"One", "Two", "Three", "Four", "Five", "Six", 
          "Seven", "Eight", "Nine", "Ten"};
       private static final int MAIN_WIDTH = 315;
       private static final int MAIN_HEIGHT = 700;
       private static final int GAP = 45;
       private static final Component PLACE_HOLDER = Box.createVerticalStrut(380);
       private JPanel displayPanel = new JPanel();
       private JScrollPane displayScrollPane = new JScrollPane(displayPanel, 
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
       private JTextField[] fields = new JTextField[LABELS.length];
    
       public MainFrameB() {
          displayPanel.setLayout(new GridBagLayout());
          int dpGap = 5;
          displayPanel.setBorder(BorderFactory.createEmptyBorder(dpGap , dpGap, dpGap, dpGap));
          for (int i = 0; i < LABELS.length; i++) {
             fields[i] = new JTextField(10);
             fields[i].addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                   fieldFocusGained(e);
                }
             });
             displayPanel.add(new JLabel(LABELS[i] + ":"), getGbc(0, i));
             displayPanel.add(fields[i], getGbc(1, i));
          }
          
          setPreferredSize(new Dimension(MAIN_WIDTH, MAIN_HEIGHT));
          setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
          setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
          add(displayScrollPane);
          
          add(PLACE_HOLDER); // delete later
       }
    
       private void fieldFocusGained(FocusEvent e) {
          JTextField field = (JTextField)e.getSource();
          Rectangle rect = field.getBounds();
          displayPanel.scrollRectToVisible(new Rectangle(0, 0, 10, 10)); // to go to very top
          displayPanel.scrollRectToVisible(rect);
       }
    
       private GridBagConstraints getGbc(int gridX, int gridY) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = gridX;
          gbc.gridy = gridY;
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
          gbc.weightx = 1.0;
          gbc.weighty = 1.0;
          gbc.anchor = (gridX == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
          gbc.fill = (gridX == 0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;
          gbc.insets = new Insets(10, 5, 10, 5);
          return gbc;
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("MainFrameB");
          frame.getContentPane().add(new MainFrameB());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }


    I thank you for providing that piece of code, I may make some use of it if I have the time - although you're calling a quite a few methods that I know nothing of and also methods like ".pack()" (which I read restores the component to it's original position - which I don't see necessary unless something isn't coded right but I'm probably very wrong in that assumption) so I'm not sure I'll be able to understand it within the timespan I have left.

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Muskar View Post
    although you're calling a quite a few methods that I know nothing of and also methods like ".pack()" (which I read restores the component to it's original position - which I don't see necessary unless something isn't coded right but I'm probably very wrong in that assumption) so I'm not sure I'll be able to understand it within the timespan I have left.
    pack renders the gui components without yet making them visible, tells the layout managers to do their thing -- layout the components that their responsible for and held in their container, and then resizes the GUI to accommodate all the components. You will want to get away from using null layouts and using layout managers, and then pack will become invaluable.

  16. #16
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    pack renders the gui components without yet making them visible, tells the layout managers to do their thing -- layout the components that their responsible for and held in their container, and then resizes the GUI to accommodate all the components. You will want to get away from using null layouts and using layout managers, and then pack will become invaluable.
    Although it all sounds very good, it won't be before later, since I'm following my education's ways and even though I really want to learn all about it, I really only can learn so much additional content beside what I learn in school - because of the amount of homework I get. Now, of course, this is the last project before the christmas-holidays so I'll have loads of time there - so I might have a look at layouts at that point - although to be honest I'm currently prioritizing perfecting non-gui-related code.

    Now, to be on-topic, I may have the time to test the setBounds method and setRectToVisible before handing the project in, and I'll return with the result if that happens.

  17. #17
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    So, I fixed the issue actually - I used JPanels and used the following method to scroll with:
    Java Code:
    createContactScrollPane.getVerticalScrollBar().setValue(pixels);
    Where 'createContactScrollPane' is the JScrollpane that contains the JPanel and 'pixels' is the amount of pixels it should be scrolled (in my case 0 sets it to the top and 305 sets it to the bottom).
    Use getMaximum() and getMinimum() (on the VerticalScrollBars, not the JScrollpane itself) to get their minimum and maximum pixel values.
    Although, this solution will only work when the JPanel never changes size, because as far as I'm aware, the "setValue()" method sets the amount of pixels the ScrollBar should scroll, not how many pixels the JPanel inside the JScrollPane should be scrolled.

    To Moderators:
    I'd like to put the following tags to this topic:
    JScrollpane, JLabel, JPanel, JTable, Viewport

    NEW PROBLEM
    Now, it isn't actually over, I now also need to do be able to scroll to a certain cell in a JTable - and it doesn't seem to have a method like "ensureIndexIsVisible" like the JList does.

    My first guess will be that I can use my solution from the JPanel-problem and make a method that calculates the increment per click by how big the maximum and minimum size is but I will have to do some testing to see if that'll work.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Muskar View Post
    To Moderators:
    I'd like to put the following tags to this topic:
    JScrollpane, JLabel, JPanel, JTable, Viewport
    Done.


    NEW PROBLEM
    Now, it isn't actually over, I now also need to do be able to scroll to a certain cell in a JTable - and it doesn't seem to have a method like "ensureIndexIsVisible" like the JList does.

    My first guess will be that I can use my solution from the JPanel-problem and make a method that calculates the increment per click by how big the maximum and minimum size is but I will have to do some testing to see if that'll work.
    I don't know the canonical solution for this, but have you tried to get the cell's Rectangle via getCellRect and then calling scrollRectToVisible on the JTable? That method really is quite useful.

    If this suggestion doesn't work, I suggest you create and post an SSCCE that would let us experiment and modify your code.

  19. #19
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Done.




    I don't know the canonical solution for this, but have you tried to get the cell's Rectangle via getCellRect and then calling scrollRectToVisible on the JTable? That method really is quite useful.

    If this suggestion doesn't work, I suggest you create and post an SSCCE that would let us experiment and modify your code.
    Thanks a lot, it was exactly what I needed - This topic is solved then :)

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. JPanel and JLabels Not Repainting
    By phosphide in forum AWT / Swing
    Replies: 6
    Last Post: 11-13-2010, 04:17 AM
  2. can i have a JList of Jlabels?
    By chayan in forum AWT / Swing
    Replies: 3
    Last Post: 07-04-2010, 01:19 AM
  3. Overlapping JLabels
    By techbossmb in forum AWT / Swing
    Replies: 3
    Last Post: 09-21-2009, 04:21 PM
  4. problem with JLabels
    By geork in forum New To Java
    Replies: 3
    Last Post: 01-31-2008, 03:30 PM
  5. Having Trouble Aligning JLabels
    By Mark_Petrov in forum AWT / Swing
    Replies: 0
    Last Post: 01-20-2008, 06:22 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •