-2

I am new to swing. I might use a layout manager one day, but please just advise on how I can add a vertical scroll bar to my Frame. I have taken an unorthodox approach, I realize, but I'm learning. I am totally stumped, having read the API. How I would go about adding a vertical scroll bar to the following JFrame?

enter image description here

My code snippet is as follows :

import javax.swing.JScrollPane;
import java.awt.event.*;
import javax.swing.*;  
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
//import java.util.Arrays;

public class NewGameGUI implements ActionListener
{ 
  private final JRadioButton[] rb = new JRadioButton[20];
    JFrame f3;  
    JButton b;
    JLabel label1; 
    public NewGameGUI()
    {  
        label1 = new JLabel("Please choose a team");
        f3 = new JFrame("Ballon d'or");  
        f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rb[0] = new JRadioButton("Arsenal");  
        rb[1] = new JRadioButton("Aston Villa");
        rb[2] = new JRadioButton("Bournemouth");
        rb[3] = new JRadioButton("Chelsea");
        rb[4] = new JRadioButton("Crystal Palace");
        rb[5] = new JRadioButton("Everton");
        rb[6] = new JRadioButton("Leicester City");
        rb[7] = new JRadioButton("Liverpool");
        rb[8] = new JRadioButton("Manchester United");
        rb[9] = new JRadioButton("Manchester City");
        rb[10] = new JRadioButton("Newcastle United");
        rb[11] = new JRadioButton("Norwich City");
        rb[12] = new JRadioButton("Southampton");
        rb[13] = new JRadioButton("Stoke City");
        rb[14] = new JRadioButton("Sunderland");
        rb[15] = new JRadioButton("Swansea City");
        rb[16] = new JRadioButton("Tottenham Hotspur");
        rb[17] = new JRadioButton("Watford");
        rb[18] = new JRadioButton("West Brom");
        rb[19] = new JRadioButton("West Ham");

        label1.setBounds(50,25,200,30);
        f3.add(label1);

        rb[0].setBounds(50,75,170,30);  
        rb[1].setBounds(50,100,170,30);  
        rb[2].setBounds(50,125,170,30);
        rb[3].setBounds(50,150,170,30);
        rb[4].setBounds(50,175,170,30);
        rb[5].setBounds(50,200,170,30);
        rb[6].setBounds(50,225,170,30);
        rb[7].setBounds(50,250,170,30);
        rb[8].setBounds(50,275,170,30);
        rb[9].setBounds(50,300,170,30);
        rb[10].setBounds(50,325,170,30);
        rb[11].setBounds(50,350,170,30);
        rb[12].setBounds(50,375,170,30);
        rb[13].setBounds(50,400,170,30);
        rb[14].setBounds(50,425,170,30);
        rb[15].setBounds(50,450,170,30);
        rb[16].setBounds(50,475,170,30);
        rb[17].setBounds(50,500,170,30);
        rb[18].setBounds(50,525,170,30);
        rb[19].setBounds(50,550,170,30);

       // JScrollPane pane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

       // f3.setContentPane(pane);

        ButtonGroup bg=new ButtonGroup();  
        bg.add(rb[0]);
        bg.add(rb[1]);
        bg.add(rb[2]);  
        bg.add(rb[3]); 
        bg.add(rb[4]); 
        bg.add(rb[5]); 
        bg.add(rb[6]); 
        bg.add(rb[7]); 
        bg.add(rb[8]); 
        bg.add(rb[9]); 
        bg.add(rb[10]); 
        bg.add(rb[11]); 
        bg.add(rb[12]); 
        bg.add(rb[13]); 
        bg.add(rb[14]);
        bg.add(rb[15]);
        bg.add(rb[16]);
        bg.add(rb[17]);
        bg.add(rb[18]);
        bg.add(rb[19]);

        b = new JButton("OK");
        b.setBounds(300,300,180,30);  
        b.addActionListener(this);
        f3.add(rb[0]);
        f3.add(rb[1]);
        f3.add(rb[2]);
        f3.add(rb[3]);
        f3.add(rb[4]);
        f3.add(rb[5]);
        f3.add(rb[6]);
        f3.add(rb[7]);
        f3.add(rb[8]);
        f3.add(rb[9]);
        f3.add(rb[10]);
        f3.add(rb[11]);
        f3.add(rb[12]);
        f3.add(rb[13]);
        f3.add(rb[14]);
        f3.add(rb[15]);
        f3.add(rb[16]);
        f3.add(rb[17]);
        f3.add(rb[18]);
        f3.add(rb[19]);
        f3.add(b);

        f3.setSize(700,700);  

        f3.setLayout(null);  
        f3.setVisible(true);  
    }

    public void setFrame(JFrame f3){
        this.f3 = f3;
    }
    public JFrame getFrame(){

    return f3;
    }
            public void actionPerformed(ActionEvent e)
            {  
                if(rb[0].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[0].getText());  
                }  
                if(rb[1].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[1].getText()); 
                } 
                if(rb[2].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[2].getText()); 
                }  
                if(rb[3].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[3].getText()); 
                }
                if(rb[4].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[4].getText()); 
                }
                if(rb[5].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[5].getText()); 
                }
                if(rb[6].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[6].getText()); 
                }
                if(rb[7].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[7].getText()); 
                }
                if(rb[8].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[8].getText()); 
                }
                if(rb[9].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[9].getText()); 
                }
                if(rb[10].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[10].getText()); 
                }
                if(rb[11].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[11].getText()); 
                }
                if(rb[12].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[12].getText()); 
                }
                if(rb[13].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[2].getText()); 
                }
                if(rb[14].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[14].getText()); 
                }
                if(rb[15].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[15].getText()); 
                }
                if(rb[16].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[16].getText()); 
                }
                if(rb[17].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[17].getText()); 
                }
                if(rb[18].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[18].getText()); 
                }
                if(rb[19].isSelected())
                {
                   f3.dispose();
                   JOptionPane.showMessageDialog(f3,"You chose : " + rb[19].getText()); 
                }  
            }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    Possible duplicate of [How to add scrollbar in JFrame with null layout?](http://stackoverflow.com/questions/18893369/how-to-add-scrollbar-in-jframe-with-null-layout) – MasterBlaster Jul 01 '16 at 23:14
  • 3
    "*I might use a layout manager one day*" Make that day today. There are tons of examples on this site and in the tutorials and its not harder than null layout. You'll do better asking questions about that attempt than this. – user1803551 Jul 02 '16 at 00:35
  • 1
    I'm voting to close this question as off-topic because the person asking has already ruled out the correct strategy (i.e. 'use layout managers'). – Andrew Thompson Jul 02 '16 at 00:52
  • As an aside, a cursory look at what the code is doing suggests this top level container should be a modal dialog rather than a frame. – Andrew Thompson Jul 02 '16 at 01:09

2 Answers2

3
  1. Use nested layouts, as suggested by @Andrew Thompson. In the example below,

    • The mainPanel uses GridLayout(1, 0) with one row and an arbitrary number of columns for the team panel and OK button.

    • The teamPanel uses GridLayout(0, 1) with an arbitrary number of rows and one column for the team radio buttons.

  2. Use List, which implements Iterable, to simplify code using for-each. In the example below,

    • A List<String> holds the team names.

    • A List<JRadioButton> named list holds the JRadioButton for each team.

    • A loop through names constructs the JRadioButton instances and adds them to the list, ButtonGroup and teamPanel.

    • A loop through list in the OK button handler identifies the selected JRadioButton.

imagee

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

/**
 * @see https://stackoverflow.com/a/38157536/230513
 */
public class Test {

    List<String> names = Arrays.asList("Arsenal", "Aston Villa", "Bournemouth",
        "Chelsea", "Crystal Palace", "Everton", "Leicester City", "Liverpool",
        "Manchester United", "Manchester City", "Newcastle United",
        "Norwich City", "Southampton", "Stoke City", "Sunderland",
        "Swansea City", "Tottenham Hotspur", "Watford", "West Brom", "West Ham");

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mainPanel = new JPanel(new GridLayout(1, 0));
        JPanel teamPanel = new JPanel(new GridLayout(0, 1));
        List<JRadioButton> list = new ArrayList<>();
        ButtonGroup bg = new ButtonGroup();
        for (String name : names) {
            JRadioButton jrb = new JRadioButton(name);
            list.add(jrb);
            bg.add(jrb);
            teamPanel.add(jrb);
        }
        teamPanel.setBorder(BorderFactory.createTitledBorder("Please choose a team."));
        mainPanel.add(new JScrollPane(teamPanel));
        JPanel okPanel = new JPanel(new GridBagLayout());
        JButton okButton = new JButton(new AbstractAction("OK") {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (JRadioButton jrb : list) {
                    if (jrb.isSelected()) {
                        JOptionPane.showMessageDialog(f, "You chose " + jrb.getText());
                    }
                }
            }
        });
        okButton.setFont(okButton.getFont().deriveFont(36f));
        okPanel.add(okButton);
        mainPanel.add(okPanel);
        f.add(mainPanel);
        f.pack();
        f.setSize(400, list.get(0).getHeight() * 16);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

This GU is trivial to create by combining layouts (though it could also be done using a single GridBagLayout or GroupLayout).

For the combined layout, look to put the radio butons into a single column grid layout. Put that panel in a scroll pane in the center of a border layout that has the label in the page start constraint. Put that panel (with border layout) in the line start position of another border layout. Put the button in a grid bag layout in the center of the outer border layout. Done.

This is my implementation of that strategy:

The numbers provided to the layout managers when constructed, as well as the empty border around the button & the margin used inside the button, can all be adjusted to provide more/less white space.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class NewGameGUIUsingLayouts {

    private JComponent ui = null;
    public static final String[] TEAM_NAMES = {
        "Arsenal", "Aston Villa", "Bournemouth", "Chelsea",  "Crystal Palace", 
        "Everton", "Leicester City", "Liverpool", "Manchester United", 
        "Manchester City", "Newcastle United",  "Norwich City", "Southampton",
        "Stoke City", "Sunderland", "Swansea City", "Tottenham Hotspur",
        "Watford", "West Brom", "West Ham"
    };

    NewGameGUIUsingLayouts() {
        initUI();
    }

    public void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(20, 20, 20, 20));

        JPanel teamSelectorPanel = new JPanel(new GridLayout(0, 1, 5, 10));
        ButtonGroup teamGroup = new ButtonGroup();
        for (String s : TEAM_NAMES) {
            JRadioButton radioButton = new JRadioButton(s);
            teamGroup.add(radioButton);
            teamSelectorPanel.add(radioButton);
        }
        JPanel lineStartPanel = new JPanel(new BorderLayout(20, 20));
        ui.add(lineStartPanel, BorderLayout.LINE_START);
        lineStartPanel.add(new JScrollPane(
                teamSelectorPanel, 
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), 
                BorderLayout.CENTER);
        lineStartPanel.add(
                new JLabel("Please choose a team"), BorderLayout.PAGE_START);
        JButton okButton = new JButton("OK");
        okButton.setMargin(new Insets(20, 50, 20, 50));
        okButton.setFont(okButton.getFont().deriveFont(50f));
        JPanel centerButtonPanel = new JPanel(new GridBagLayout());
        centerButtonPanel.setBorder(new EmptyBorder(100,100,100,100));
        centerButtonPanel.add(okButton);
        ui.add(centerButtonPanel, BorderLayout.CENTER);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                NewGameGUIUsingLayouts o = new NewGameGUIUsingLayouts();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                Dimension d = f.getSize();
                Dimension shortDimension = new Dimension(
                        (int)d.getWidth(), 
                        (int)d.getHeight()-200);
                f.setMinimumSize(shortDimension);
                f.setSize(shortDimension);

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433