Adding JButton, JTextField to scroll pane...

I have developed an appln in which I have added JPanel to JFrame.
To this JPanel I m adding JButton & JTextField. But the JButton & JTextField are increasing dynamically in my appln[according to DBMS query]. So I wanted to use scrolpane or something like so that the window can be scrolled vertically to view all the components[JButton & JTextField]. I m developing this as a standalone appln.
Plz help..
Thanking in advance.

Thanx fouadk ,
But my problem still persists. Now though I m able to add JPanel to JScrollPane, but when the components in the JPanel increase than the height of the Pane, the components at the dowm are not visible unless I resize the window by manually dragging the corners. Actually I wanted to keep the size of the window constant and make use of the VERTICAL SCROLLBAR.
Plz help.
Thanking in advance.
Following is code:
import javax.swing.*;
public class testt extends JFrame {
private JPanel p = new JPanel();
private JScrollPane sp = new JScrollPane(p
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JButton b[] = new JButton[15];
public testt() {
super("TEST");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 400);
setLocation(50, 20);
this.add(sp);
p.setLayout(null);
sp.setAutoscrolls(true);
for(int i = 0, y = 10; i < 15; i++, y += 40)
     b[i] = new JButton("BUTTON "+ (i+1));
     b.setBounds(10,y,100,20);
     p.add(b[i]);
public static void main(String[] args) {
testt t = new testt();
t.setVisible(true);

Similar Messages

  • Problem with adding text area in scroll pane

    hi , i have been facing this funny problem , but cant able to get solution.
    the problem is i am trying to add text area in scroll pane , but when i add textarea in scroll pane using scrollpane.add(textarea) that text area remain disable always. i tried making it enable explicility but that code is not working.

    You don't use the add(...) method for JScrollPane. Use:
    a) new JScrollPane( textArea );
    b) scrollPane.getViewport().setView( textArea );

  • Updating a Scroll Pane

    Hi!
    Im a newbie to swing so hopefully theres a simple solution to this.
    Im beginning with a JScrollPane that has no data in it and is presented as such. However, when the relevant data has been selected i want to populate the scrollpane with the extracted data.
    I ve started off with an empty JList that i ve instantiated in the constructor and placed in the JScrollPane. When the relevant button is pressed the list is updated with the new data, but im not sure how i can get also update scrollpane with the new list, with the results shown on screen.
    Any help or code on how to do this would be much appreciated. Thanks in advance for any help.
    Zidane

    For this situation Frist u take a JScrollPane
    and take a JList in the JScrollPane when the
    element is added in the list it will atomaticaly
    give the effect
    this code help for list and Scroll Pane
    Hope this will help you
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ListDemo extends JFrame
                          implements ListSelectionListener {
        private JList list;
        private DefaultListModel listModel;
        private static final String hireString = "Hire";
        private static final String fireString = "Fire";
        private JButton fireButton;
        private JTextField employeeName;
        public ListDemo() {
            super("ListDemo");
            listModel = new DefaultListModel();
            listModel.addElement("Alison Huml");
            listModel.addElement("Kathy Walrath");
            listModel.addElement("Lisa Friendly");
            listModel.addElement("Mary Campione");
            //Create the list and put it in a scroll pane
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            JButton hireButton = new JButton(hireString);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(new HireListener());
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(new HireListener());
            String name = listModel.getElementAt(
                                  list.getSelectedIndex()).toString();
            employeeName.setText(name);     
            //Create a panel that uses FlowLayout (the default).
            JPanel buttonPane = new JPanel();
            buttonPane.add(employeeName);
            buttonPane.add(hireButton);
            buttonPane.add(fireButton);
            Container contentPane = getContentPane();
            contentPane.add(listScrollPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
        class FireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                //so go ahead and remove whatever's selected.
                int index = list.getSelectedIndex();
                listModel.remove(index);
                int size = listModel.getSize();
                if (size == 0) {
                //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else {
                //Adjust the selection.
                    if (index == listModel.getSize())//removed item in last position
                        index--;
                    list.setSelectedIndex(index);   //otherwise select same index
        //This listener is shared by the text field and the hire button
        class HireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //User didn't type in a name...
                if (employeeName.getText().equals("")) {
                    Toolkit.getDefaultToolkit().beep();
                    return;
                int index = list.getSelectedIndex();
                int size = listModel.getSize();
                //If no selection or if item in last position is selected,
                //add the new hire to end of list, and select new hire.
                if (index == -1 || (index+1 == size)) {
                    listModel.addElement(employeeName.getText());
                    list.setSelectedIndex(size);
                //Otherwise insert the new hire after the current selection,
                //and select new hire.
                } else {
                    listModel.insertElementAt(employeeName.getText(), index+1);
                    list.setSelectedIndex(index+1);
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
                    employeeName.setText("");
                } else {
                //Selection, update text field.
                    fireButton.setEnabled(true);
                    String name = list.getSelectedValue().toString();
                    employeeName.setText(name);
        public static void main(String s[]) {
            JFrame frame = new ListDemo();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

  • IS IT POSSIBLE TO ADD A SCROLL PANE TO A PANEL??

    Hi, Im trying to add a scroll pane to a panel but when I compile the code and try to open the form - a 'Illegal Argument Exception' is produced. Can anyone tell me whether it is possible to add a scroll pane the actual panel itself and also the code to do this.     
    Many Thanks, Karl.
    I have added some sample code I have created -
    public RequestForm(RequestList inC)throws SQLException{
              inRequestList = inC;
              displayForm();
              displayFields();
              displayButtons();
              getContentPane().add(panel);
              setVisible(true);
         public void displayForm() throws SQLException{
              setTitle("Request Form");
              setSize(600,740);
              // Center the frame
              Dimension dim = getToolkit().getScreenSize();
              setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
              getContentPane().setLayout(new BorderLayout());
              Border etched = BorderFactory.createEtchedBorder();
              panel = new JPanel();
              panel.setLayout( null );
              //panel.setBackground(new Color(1,90,50));
              Border paneltitled = BorderFactory.createTitledBorder(etched,"");
              panel.setBorder(paneltitled);
              scrollPane1 = new JScrollPane(panel);
              scrollPane1.setBounds(0, 0, 600, 740);
              panel.add(scrollPane1);
    }

    Hi all,
    I am still having trouble here. would it be posible to add a scrollpanel to this form? Can anyone provide me with a working piece of code so I see how it actually works.
    Any help would be greatly appreciated.
    Many Thanks, Karl.
    Code as Follows:
    /* ADMIN HELP Manual*/
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    public class AdminHelp extends JFrame implements ActionListener{
         private JButton exit;
         private JLabel heading1, help;
         private JPanel panel;
         Font f = new Font("Times New Roman", Font.BOLD, 30);
         private JScrollPane scroll;
         public AdminHelp(){
              setTitle("ADMIN Help Manual");
              setSize(400,325);
              // Center the frame
              Dimension dim = getToolkit().getScreenSize();
              setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
              panel = new JPanel();
              panel.setLayout(null);
              exit = new JButton("Close");
              exit.setBounds(280,260,100,20);
              exit.addActionListener(this);
              panel.add(exit);
              exit.setToolTipText("Click here to close and return to the main menu");
              getContentPane().add(panel);
              show();
              public void actionPerformed(ActionEvent event){
              Object source = event.getSource();
                   if (source == exit){
                        dispose();
              public static void main(String[] args){
                   AdminHelp frame = new AdminHelp();
                   frame.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                   System.exit(0);

  • Need help with a scroll pane

    Hello all. I am trying to get a scroll pane to work in an application that I have built for school. I am trying to get an amortization table to scroll through for a mortgage calculator. It isn't recognizing my scrollpane and I am not sure why. Could someone give me a push in the right direction.
    import javax.swing.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    public class MortCalcWeek3 extends JFrame implements ActionListener
         DecimalFormat twoPlaces = new DecimalFormat("#,###.00");//number format
         int L[] = {7, 15, 30};
         double I[] = {5.35, 5.5, 5.75};
         double P, M, J, H, C, Q;
         JPanel panel = new JPanel ();//creates the panel for the GUI
         JLabel title = new JLabel("Mortgage Calculator");
         JLabel PLabel = new JLabel("Enter the mortgage amount: ");
         JTextField PField = new JTextField(10);//field for obtaining user input for mortgage amount
         JLabel choices = new JLabel ("Choose the APR and Term in Years");
         JTextField choicestxt = new JTextField (0);
         JButton calcButton = new JButton("Calculate");
         JTextField payment = new JTextField(10);
         JLabel ILabel = new JLabel("Annual Percentage Rate: choose one");
         String [] IChoice = {I[0] + "", I[1] + "", I[2] + ""};
         JComboBox IBox = new JComboBox(IChoice);
         JLabel LLabel = new JLabel("Term (in years): choose one");
         String [] LChoice = {L[0] + "", L[1] + "", L[2] + ""};
         JComboBox LBox = new JComboBox(LChoice);
         JLabel amortBox = new JLabel("Amortiaztion Table");
         JScrollPane amortScroll = new JScrollPane(amortBox);
         public MortCalcWeek3 () //creates the GUI window
                        super("Mortgage Calculator");
                        setSize(300, 400);
                        setBackground (Color.white);
                        setForeground(Color.blue);
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        //Creates the container
                        Container contentPane = getContentPane();
                        FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
                        panel.setLayout(fresh);
                        //identifies trigger events
                        calcButton.addActionListener(this);
                        PField.addActionListener(this);
                        IBox.addActionListener(this);
                        LBox.addActionListener(this);
                        panel.add(PLabel);
                        panel.add(PField);
                        panel.add(choices);
                        panel.add(choicestxt);
                        panel.add(ILabel);
                        panel.add(IBox);
                        panel.add(LLabel);
                        panel.add(LBox);
                        panel.add(calcButton);
                        panel.add(payment);
                        panel.add(amortBox);
                        payment.setEditable(false);
                        panel.add(amortScroll);
                        setContentPane(panel);
                        setVisible(true);
         }// end of GUI info
              public void actionPerformed(ActionEvent e) {
                   MortCalcWeek3();     //calls the calculations
              public void MortCalcWeek3() {     //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble((String) IBox.getSelectedItem());
                   double L = Double.parseDouble((String) LBox.getSelectedItem());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
         //public void amort() {
                   //int N = (L * 12);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  String showAmort = twoPlaces.format(H + C + Q);
                                amortScroll(showAmort);
              public static void main(String[] args) {
              MortCalcWeek3 app = new MortCalcWeek3();
    }//end main
    }//end the programI appreciate any help you may provide.

         JLabel amortBox = new JLabel("Amortiaztion Table");
         JScrollPane amortScroll = new JScrollPane(amortBox);The argument passed to a JScrollPane constructor specifies what's inside the scroll pane. Here, it seems like you're trying to create a scroll pane that displays a JLabel.
    Also, I'm not sure what you're trying to do here:
    amortScroll(showAmort);I don't see a method named "amortScroll".
    You need to make a JTextArea, pass that into the JScrollPane's constructor, and add the JScrollPane to your frame.

  • New to Applets: Problems wiht writing to files and with scroll panes.

    Hi, I've recently graduated from university and so I have limited experience in java programming and I'm having some trouble with JApplets (this is the first time I've made one). I'm trying to make a simple program that will allow users to pick one of a few background images from a list (a list of jpanels within a scroll pane) then at the click of a button will output a CSS with the background tag set to the image location. This is for use on a microsoft sharepoint site where each user has a My-Sit area which I want to be customizable.
    So far I've been creating this program as an application rather than a JApplet and just having another class that extends the JApplet Class which then displays the JFrame from the GUI Class. This initially didnt work because I was trying to add a window to a container so I kept programming it as an application until I got it working before trying to convert it to a JApplet. I solved the previous problem by changing my GUI class to extend JPanel instead of JFrame and it now displays correctly but with a coupe of issues.
    Firstly the applet will not create/write to the CSS file. I read that applets couldnt read/write to the users file system but they could to their own. The file I wish to write to is kept on the same machine as the applet so I'm not sure why this isn't working.
    Secondly the scroll panel is no longer working properly. This worked fine when I was still running the program as an application when the GUI still extended JFrame instead of JPanel (incidentally the program no longer runs as an application in this state) but now the scroll bar does not appear. This is a problem since I want the applet to remain the same size on the page even if I decide to add more backgrounds to the list. I tried setting the applet height/width to smaller values in the html file to see if the scroll bar would appear if the area was smaller than the GUI should be, but this just meant the bottom off the applet was cut off.
    Could anyone offer any suggestion as to why these thigns arnt working and how to fix them? If necessary I can post my source code here. Thanks in advance.

    Ok, well my program is made up of 4 classes, I hope this isnt too much to be posting. If any explaination is needed then I'll post that next. Theres lots of print lines scattered aroudn due to me trying to fix this and theres some stuff commented out from when the program used to be an application isntead of an applet.
    GUI Class, this was the main class until I made a JApplet Class
    public class AppletGUI extends JPanel{
        *GUI Components*
        //JFrames
        JFrame mainGUIFrame = new JFrame();
        JFrame changeBackgroundFrame = new JFrame();
        //JPanels (Sub-panels are indented)
        JPanel changeBackgroundJP = new JPanel(new BorderLayout());
            JPanel changeBackgroundBottomJP = new JPanel(new GridLayout(1,2));
        JPanel backgroundJP = new JPanel(new GridLayout(1,2));
        JPanel selectBackground = new JPanel(new GridLayout(1,2));
        //Jbuttons
        JButton changeBackgroundJB = new JButton("Change Background");
        JButton defaultStyleJB = new JButton("Reset Style");
        //JLabels
        JLabel changeBackgroundJL = new JLabel("Choose a Background from the Menu");
        JLabel backgroundJL = new JLabel();
        //JScrollPane
        JScrollPane backgroundList = new JScrollPane();
            JPanel backgroundListPanel = new JPanel(new GridLayout());
        //Action Listeners
        ButtonListener bttnLstnr = new ButtonListener();
        //Controllers
        CSSGenerator cssGenerator = new CSSGenerator();
        Backgrounds backgroundsController = new Backgrounds();
        backgroundMouseListener bgMouseListener = new backgroundMouseListener();
        //Flags
        Component selectedComponent = null;
        *Colour Changer*
        //this method is used to change the colour of a selected JP
        //selected JPs have their background darkered and when a
        //different JP is selected the previously seleced JP has its
        //colour changed back to it's original.
        public void changeColour(JPanel theJPanel, boolean isDarker){
        //set selected JP to a different colour
        Color tempColor = theJPanel.getBackground();
            if(isDarker){
                tempColor = tempColor.darker();
            else{
                tempColor = tempColor.brighter();
            theJPanel.setBackground(tempColor);
         //also find any sub-JPs and change their colour to match
         int j = theJPanel.getComponents().length;
         for(int i = 0; i < j; i++){
                String componentType = theJPanel.getComponent(i).getClass().getSimpleName();
                if(componentType.equals("JPanel")){
                    theJPanel.getComponent(i).setBackground(tempColor);
        *Populating the GUI*
        //backgroundList.add();
        //Populating the Backgrounds List
        *Set Component Size Method*
        public void setComponentSize(Component component, int width, int height){
        Dimension tempSize = new Dimension(width, height);
        component.setSize(tempSize);
        component.setMinimumSize(tempSize);
        component.setPreferredSize(tempSize);
        component.setMaximumSize(tempSize);     
        *Constructor*
        public AppletGUI() {
            //REMOVED CODE
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //Component Sizes
            //setComponentSize
            //Adding Action Listeners to Components
            System.out.println("adding actions listeners to components");
            changeBackgroundJB.addActionListener(bttnLstnr);
            defaultStyleJB.addActionListener(bttnLstnr);
            //Populating the Change Background Menu
            System.out.println("Populating the window");
            backgroundsController.populateBackgroundsData();
            backgroundsController.populateBackgroundsList();
            //loops to add background panels to the JSP
            ArrayList<JPanel> tempBackgroundsList = new ArrayList<JPanel>();
            JPanel tempBGJP = new JPanel();
            tempBackgroundsList = backgroundsController.getBackgroundsList();
            int j = tempBackgroundsList.size();
            JPanel backgroundListPanel = new JPanel(new GridLayout(j,1));
            for(int i = 0; i < j; i++){
                tempBGJP = tempBackgroundsList.get(i);
                System.out.println("Adding to the JSP: " + tempBGJP.getName());
                //Add Mouse Listener
                tempBGJP.addMouseListener(bgMouseListener);
                backgroundListPanel.add(tempBGJP, i);
            //set viewpoing
            backgroundList.setViewportView(backgroundListPanel);
            /*TESTING
            System.out.println("\n\n TESTING!\n Printing Content of SCROLL PANE \n");
            j = tempBackgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println(backgroundList.getComponent(i).getName());
            changeBackgroundJP.add(changeBackgroundJL, BorderLayout.NORTH);
            changeBackgroundJP.add(backgroundList, BorderLayout.CENTER);
            //changeBackgroundJP.add(tempBGJP, BorderLayout.CENTER);
            changeBackgroundJP.add(changeBackgroundBottomJP, BorderLayout.SOUTH);
            changeBackgroundBottomJP.add(changeBackgroundJB);
            changeBackgroundBottomJP.add(defaultStyleJB);
            System.out.println("Finsihed populating");
            //REMOVED CODE
            //adding the Background Menu to the GUI and settign the GUI options
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //this.setResizable(true);
            //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLocation(500,500);
            this.setSize(400,300);
            this.add(changeBackgroundJP);
        //REMOVED CODE
         *Main Method*
        public static void main(String[] args){
           System.out.println("Creating GUI");
           AppletGUI theGUI = new AppletGUI();
           theGUI.setVisible(true);
           System.out.println("GUI Displayed");
         *Button Listener Inner Class*
        public class ButtonListener implements ActionListener{
            //check which button is clicked
            public void actionPerformed(ActionEvent event) {
                AbstractButton theButton = (AbstractButton)event.getSource();
                //Default Style Button
                if(theButton == defaultStyleJB){
                    System.out.println("Default Style Button Clicked!");
                //Change Background Button
                if(theButton == changeBackgroundJB){
                    System.out.println("Change Background Button Clicked!");
                    String backgroundURL = cssGenerator.getBackground();
                    if(backgroundURL != ""){
                        cssGenerator.setBackgroundChanged(true);
                        cssGenerator.setBackground(backgroundURL);
                        cssGenerator.outputCSSFile();
                        System.out.println("Backgroudn Changed, CSS File Written");
                    else{
                        System.out.println("No Background Selected");
         *Mouse Listener Inner Class*
        public class backgroundMouseListener implements MouseListener{
            public void mouseClicked(MouseEvent e){
                //get component
                JPanel tempBackgroundJP = new JPanel();
                tempBackgroundJP = (JPanel)e.getComponent();
                System.out.println("Background Panel Clicked");
                //change component colour
                if(selectedComponent == null){
                    selectedComponent = tempBackgroundJP;
                else{
                    changeColour((JPanel)selectedComponent, false);
                    selectedComponent = tempBackgroundJP;
                changeColour((JPanel)selectedComponent, true);
                //set background URL
                cssGenerator.setBackground(tempBackgroundJP.getName());
            public void mousePressed(MouseEvent e){
            public void mouseReleased(MouseEvent e){
            public void mouseEntered(MouseEvent e){
            public void mouseExited(MouseEvent e){
    }JApplet Class, this is what I plugged the GUI into after I made the change from Application to JApplet.
    public class AppletTest extends JApplet{
        public void init() { 
            System.out.println("Creating GUI");
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            Container content = getContentPane();
            content.setBackground(Color.white);
            content.setLayout(new FlowLayout());
            content.add(theGUI);
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            setContentPane(theGUI);
            System.out.println("GUI Displayed");
        public static void main(String[] args){
            AppletTest at = new AppletTest();
            at.init();
            at.start();
    }The CSS Generator Class. This exists because once I have the basic program working I intend to expand upon it and add multiple tabs to the GUI, each one allowing the user to change different style options. Each style option to be changed will be changed wit ha different method in this class.
    public class CSSGenerator {
        //Variables
        String background = "";
        ArrayList<String> backgroundCSS;
        //Flags
        boolean backgroundChanged = false;
        //Sets and Gets
        //For Variables
        public void setBackground(String theBackground){
            background = theBackground;
        public String getBackground(){
            return background;
        //For Flags
        public void setBackgroundChanged(boolean isBackgroundChanged){
            backgroundChanged = isBackgroundChanged;
        public boolean getBackgroundChanged(){
            return backgroundChanged;
        //background generator
        public ArrayList<String> backgroundGenerator(String backgroundURL){
            //get the URL for the background
            backgroundURL = background;
            //creat a new array list of strings
            ArrayList<String> backgroundCSS = new ArrayList<String>();
            //add the strings for the background options to the array list
            backgroundCSS.add("body");
            backgroundCSS.add("{");
            backgroundCSS.add("background-image: url(" + backgroundURL + ");");
            backgroundCSS.add("background-color: #ff0000");
            backgroundCSS.add("}");
            return backgroundCSS;
        //Write CSS to File
        public void outputCSSFile(){
            try{
                //Create CSS file
                System.out.print("creating file");
                FileWriter cssWriter = new FileWriter("C:/Documents and Settings/Gwilym/My Documents/Applet Data/CustomStyle.css");
                System.out.print("file created");
                System.out.print("creating buffered writer");
                BufferedWriter out = new BufferedWriter(cssWriter);
                System.out.print("buffered writer created");
                //check which settings have been changed
                //check background flag
                if(getBackgroundChanged() == true){
                    System.out.print("retrieving arraylist");
                    ArrayList<String> tempBGOptions = backgroundGenerator(getBackground());
                    System.out.print("arraylist retrieved");
                    int j = tempBGOptions.size();
                    for(int i = 0; i < j ; i++){
                        System.out.print("writing to the file");
                        out.write(tempBGOptions.get(i));
                        out.newLine();
                        System.out.print("written to the file");
                out.close();
            }catch (Exception e){//Catch exception if any
                System.out.println("Error: Failed to write CSS file");
        /** Creates a new instance of CSSGenerator */
        public CSSGenerator() {
    }The Backgrounds Class. This class exists because I didnt want there to just be a hardcoded lsit of backgrounds, I wanted it to be possible to add new ones to the list without simply lettign users upload their own images (since the intended users are kids and this sharepoint site is used for educational purposes, I dont want them uplaoded inapropraite backgrounds) but I do want the site admin to be able to add more images to the list. for this reason the backgrounds are taken from a list in a text file that will be stored in the same location as the applet, the file specifies the background name, where it is stored, and where a thumbnail image is stored.
    public class Backgrounds {
        //Array Lists
        private ArrayList<JPanel> backgroundsList;
        private ArrayList<String> backgroundsData;
        //Set And Get Methods
        public ArrayList getBackgroundsList(){
            return backgroundsList;
        //ArrayList Population Methods
        public void populateBackgroundsData(){
            //decalre the input streams and create a new fiel hat points to the BackgroundsData file
            File backgroundsDataFile = new File("C:/Documents and Settings/Gwilym/My Documents/Applet Data/BackgroundsData.txt");
            FileInputStream backgroundsFIS = null;
            BufferedInputStream backgroundsBIS = null;
            DataInputStream backgroundsDIS = null;
            try {
                backgroundsFIS = new FileInputStream(backgroundsDataFile);
                backgroundsBIS = new BufferedInputStream(backgroundsFIS);
                backgroundsDIS = new DataInputStream(backgroundsBIS);
                backgroundsData = new ArrayList<String>();
                String inputtedData = null;
                //loops until it reaches the end of the file
                while (backgroundsDIS.available() != 0) {
                    //reads in the data to be stored in an array list
                    inputtedData = backgroundsDIS.readLine();
                    backgroundsData.add(inputtedData);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsData()");
            int j = backgroundsData.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsData.get(i));
            System.out.println("\n\n");
            //close all stremas
            backgroundsFIS.close();
            backgroundsBIS.close();
            backgroundsDIS.close();
            } catch (FileNotFoundException e) {
                System.out.println("Error: File Not Found");
            } catch (IOException e) {
                System.out.println("Error: IO Exception Thrown");
        public void populateBackgroundsList(){
            backgroundsList = new ArrayList<JPanel>();
            int j = backgroundsData.size();
            System.out.println("number of backgrounds = " + j);
            backgroundsList = new ArrayList<JPanel>();
            for(int i = 0; i < j; i++){
                String tempBackgroundData = backgroundsData.get(i);
                JPanel backgroundJP = new JPanel(new GridLayout(1,2));
                JLabel backgroundNameJL = new JLabel();               
                JLabel backgroundIconJL = new JLabel();
                //split the string string and egt the background name and URL
                String[] splitBGData = tempBackgroundData.split(",");
                String backgroundName = splitBGData[0];
                String backgroundURL = splitBGData[1];
                String backgroundIcon = splitBGData[2];
                System.out.println("\nbackgroundName = " + backgroundName);
                System.out.println("\nbackgroundURL = " + backgroundURL);
                System.out.println("\nbackgroundIcon = " + backgroundIcon + "\n");
                backgroundNameJL.setText(backgroundName);
                backgroundIconJL.setIcon(new javax.swing.ImageIcon(backgroundIcon));
                backgroundJP.add(backgroundNameJL);
                backgroundJP.add(backgroundIconJL);
                backgroundJP.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
                //Name the JP as the background URL so it can be found
                //May be useful sicne the data file may need to contain 3 fields in future
                //this is incase the preview image (icon) is different from the acctual background
                //most liekly in the case of more complex ppictures rather then repeating patterns
                backgroundJP.setName(backgroundURL);
                //Add the JP to the Array List
                backgroundsList.add(backgroundJP);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsList()");
            j = backgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsList.get(i));
            System.out.println("\n\n");
    }So thats my program so far, if theres anythign that needs clarifying then please jsut ask. Thank you very much for the help!

  • Adding buttons into a scolling pane

    Hi
    I'm trying to create a class that allows for the adding of button to a scrolling pane.
    Here is my code so far
    public class Menu extends JPanel
         JButton a = new JButton("sdsd");
         JButton b = new JButton("sdssd");
         Menu()
              JScrollPane as = new JScrollPane();
              as.setPreferredSize(new Dimension(150,150));
              a.setPreferredSize(new Dimension(15,15));
              as.add(a);
              as.add(b);
              add(as);
    }However all i get is a rectangle so I'm doing something wrong.
    Can anyone offer any help as to why it's not working?
    thanks

    something like this:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class BtnScrollPaneTest extends JPanel
        private JButton buttonA = new JButton("Button A");
        private JButton buttonB = new JButton("Button B");
        public BtnScrollPaneTest()
            setPreferredSize(new Dimension(150, 150));
            setLayout(new BorderLayout());
            JScrollPane scrollPane = new JScrollPane();
            JPanel viewportPane = new JPanel(new GridLayout(0, 1, 5, 5));
            viewportPane.setPreferredSize(new Dimension(100, 300));
            JPanel buttonPanel1 = new JPanel();
            buttonPanel1.add(buttonA);
            viewportPane.add(buttonPanel1);
            JPanel buttonPanel2 = new JPanel();
            buttonPanel2.add(buttonB);
            viewportPane.add(buttonPanel2);
            scrollPane.getViewport().add(viewportPane);
            add(scrollPane, BorderLayout.CENTER);
        private static void createAndShowGUI()
            JFrame frame = new JFrame("SwingFoo2 Application");
            frame.getContentPane().add(new BtnScrollPaneTest());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Missing Scroll Pane

    Could someone please tell me why in the following code the Scroll Pane does not appear? The code refers to two other classes I didn't include here although I've added comments to explain how they're used.
    Thanks very much.
    public class VPA extends JPanel implements ListSelectionListener {
    static DB2Connect vpaDB2connect = null;
    JPanel contentPanel;
    JPanel subPanel;
    JList listOfData;
    DataList dataList;
    VPAsql vpaSQL;
    public VPA() {
    vpaDB2connect = new DB2Connect(); // a DB2 database connection
    vpaDB2connect.makeConnection();
    subPanel = new JPanel();
    subPanel.setLayout(new BoxLayout(subPanel,BoxLayout.Y_AXIS));
    subPanel.add(Box.createRigidArea(new Dimension(0,5)));
    dataList = new DataList(vpaDB2connect); //returns a list of data
    listOfData = dataList.getList(); // listOfData is a JList
    listOfData.addListSelectionListener(this);
    JScrollPane scrollPane = new JScrollPane(listOfData);
    scrollPane.setPreferredSize(new Dimension(250,80));
    scrollPane.setMinimumSize(new Dimension(250,80));
    scrollPane.setAlignmentX(LEFT_ALIGNMENT);
    subPanel.add(listOfData);
    subPanel.add(scrollPane);
    contentPanel = new JPanel();
    contentPanel.add(subPanel,BorderLayout.CENTER);
    public void valueChanged(ListSelectionEvent e) {}
    public static void main(String[] args) {                
    VPA vpa = new VPA();
    JFrame frame = new JFrame("VPA");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.setContentPane(vpa.contentPanel);
    frame.pack();
    frame.setVisible(true);
    }

    The suggested solution about adding the following line
    to my code does not make any difference.
    frame.setContentPane(vpa);
    I'm still looking for an answer on why the Scroll Pane
    is not being displayed. If you havent fixed the prob then why did you give Duke Dollars to someone? anyway i don't see the probem Try this out:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class VPA extends JPanel
      JPanel contentPanel;
      JPanel subPanel;
      JList listOfData;
      public VPA()
        String[] list = {"one", "two", "three", "four", "five", "Six", "seven", "eight", "nine", "ten"};
        listOfData = new JList(list);
        subPanel = new JPanel();
        subPanel.setLayout(new BoxLayout(subPanel,BoxLayout.Y_AXIS));
        subPanel.add(Box.createRigidArea(new Dimension(0,5)));
        JScrollPane scrollPane = new JScrollPane(listOfData);
        scrollPane.setPreferredSize(new Dimension(250,80));
        scrollPane.setMinimumSize(new Dimension(250,80));
        scrollPane.setAlignmentX(LEFT_ALIGNMENT);
        subPanel.setBackground(Color.yellow);// to see where subPanel is in the layout
        subPanel.add(new JTextField());
        subPanel.add(scrollPane);
        contentPanel = new JPanel();
        contentPanel.setBackground(Color.orange);// to see where the contentPanel is in the layout
        contentPanel.add(subPanel,BorderLayout.CENTER);
      public static void main(String[] args)
        VPA vpa = new VPA();
        JFrame frame = new JFrame("VPA");
        frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
        System.exit(0);
       frame.setContentPane(vpa.contentPanel);
       frame.pack();
       frame.setVisible(true);

  • Scroll pane color for xp look and feel

    hi
    I am using the xp look and feel for my intranet application. Everything looks great, except for the colors of the scroll pane (added in a table) which still remains brown. I have tried setting the colors of the scroll pane, but nothing seems to work. Where is it that i am going wrong?
    Thanks

    Use this
    table.getParent().setBackground(Color.BLUE);

  • How to scroll at the bottom using scroll pane

    i am having a label in which i have added a scroll pane. dynamically i will add some text to the label. the scroll bar should move to the buttom after addition of text so that the new text added should be visible.
    please provide me a solution.

    Swap from using a JLabel to a JTextArea, then use below to set position viewed. (do this after each time you enter any text)
    yourJTextArea.setCaretPosition(yourJTextArea.getText().length());

  • Scroll pane height

    I need to set the height of a scroll pane to the sum of heights of all the child elements in it. i.e i have a scroll pane and the content of the scroll pane is vbox. The vbox has many elements in it. I want to set the scroll pane height to sum of the height of the individual cell items in it. Please let me know.
    Thanks.

    Should have said desirable not acceptable. The most desirable solution is to use standard layouts and components. But also very desirable is to not spend so much time on such a simple issue. So I have used the ScrollableFlowPanel and the static inner class was a simple drop in. The only thing I added was a call to the following to left align: setLayout(new FlowLayout(FlowLayout.LEADING));Thanks for the help.

  • Scroll pane can't align it's content

    When a Node(group fro example) is added into a scroll pane, the scroll pane automatically align the node to the upper left corner of the scroll pane's content area. How can i customize the Node's alignment(the middle center eg) in the scroll pane. When the Node's size is scaled and larger than the scroll pane's size the scroll pane's scroll bar appears, and if the Node's size shrinks and it's size becomes smaller than the scroll pane's then the Node is aligned to the middle center. it seems don't take affect if i override the scroll pane's layoutChildren method and set layoutX and layoutY property of the Node.
    If any one can give me some clue?
    thanks

    ScrollPanes are somewhat tricky to use. They don't align content, you need to use layout managers to do that or you need to layout yourself with shapes in groups using absolute co-ordinates and/or translations. The ScrollPane defines it's own viewport related coordinates and you need to layout your content within that viewport.
    How can i customize the Node's alignment(the middle center eg) in the scroll pane.Get the layoutBoundsInParent of the node, get the viewportBounds of the scrollpane and perform the translation of the node such that the center of the node is in the center of the viewportBounds (will require a little bit of basic maths to do this) by adding listeners on each property.
    When the Node's size is scaled and larger than the scroll pane's size the scroll pane's scroll bar appears, and if the Node's size shrinks and it's size becomes smaller than the scroll pane's then the Node is aligned to the middle center.Similar to above, just work with those properties.
    Not exactly a direct answer to your question, but you could try playing around with the following code if you like Saludon. It is something I wrote to learn about JavaFX's layoutbounds system. Resizing the scene and toggling items on and off will allow you to see the scroll pane. The view bounds listeners show you the properties you are interested in to achieve the effect you want.
    import javafx.application.Application;
    import javafx.beans.value.*;
    import javafx.event.*;
    import javafx.geometry.Bounds;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.effect.DropShadow;
    import javafx.scene.layout.*;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.*;
    import javafx.stage.Stage;
    public class LayoutBoundsScrollableAnchorPane extends Application  {
      // define some controls.
      final ToggleButton stroke    = new ToggleButton("Add Border");
      final ToggleButton effect    = new ToggleButton("Add Effect");
      final ToggleButton translate = new ToggleButton("Translate");
      final ToggleButton rotate    = new ToggleButton("Rotate");
      final ToggleButton scale     = new ToggleButton("Scale");
      public static void main(String[] args) { launch(args); }
      @Override public void start(Stage stage) throws Exception {
        // create a square to be acted on by the controls.
        final Rectangle square = new Rectangle(20, 30, 100, 100); //square.setFill(Color.DARKGREEN);
        square.setStyle("-fx-fill: linear-gradient(to right, darkgreen, forestgreen)");
        // show the effect of a stroke.
        stroke.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            if (stroke.isSelected()) {
              square.setStroke(Color.FIREBRICK); square.setStrokeWidth(10); square.setStrokeType(StrokeType.OUTSIDE);
            } else {
              square.setStroke(null); square.setStrokeWidth(0.0); square.setStrokeType(null);
            reportBounds(square);
        // show the effect of an effect.
        effect.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            if (effect.isSelected()) {
              square.setEffect(new DropShadow());
            } else {
              square.setEffect(null);
            reportBounds(square);
        // show the effect of a translation.
        translate.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            if (translate.isSelected()) {
              square.setTranslateX(100);
              square.setTranslateY(60);
            } else {
              square.setTranslateX(0);
              square.setTranslateY(0);
            reportBounds(square);
        // show the effect of a rotation.
        rotate.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            if (rotate.isSelected()) {
              square.setRotate(45);
            } else {
              square.setRotate(0);
            reportBounds(square);
        // show the effect of a scale.
        scale.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            if (scale.isSelected()) {
              square.setScaleX(2);
              square.setScaleY(2);
            } else {
              square.setScaleX(1);
              square.setScaleY(1);
            reportBounds(square);
        // layout the scene.
        final AnchorPane anchorPane = new AnchorPane();
        AnchorPane.setTopAnchor(square,  0.0);
        AnchorPane.setLeftAnchor(square, 0.0);
        anchorPane.setStyle("-fx-background-color: cornsilk;");
        anchorPane.getChildren().add(square);
        // add a scrollpane and size it's content to fit the pane (if it can).
        final ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(anchorPane);
        square.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
          @Override public void changed(ObservableValue<? extends Bounds> observableValue, Bounds oldBounds, Bounds newBounds) {
            anchorPane.setPrefSize(Math.max(newBounds.getMaxX(), scrollPane.getViewportBounds().getWidth()), Math.max(newBounds.getMaxY(), scrollPane.getViewportBounds().getHeight()));
        scrollPane.viewportBoundsProperty().addListener(
          new ChangeListener<Bounds>() {
          @Override public void changed(ObservableValue<? extends Bounds> observableValue, Bounds oldBounds, Bounds newBounds) {
            anchorPane.setPrefSize(Math.max(square.getBoundsInParent().getMaxX(), newBounds.getWidth()), Math.max(square.getBoundsInParent().getMaxY(), newBounds.getHeight()));
        // layout the scene.
        VBox controlPane = new VBox(10);
        controlPane.setStyle("-fx-background-color: linear-gradient(to bottom, gainsboro, silver); -fx-padding: 10;");
        controlPane.getChildren().addAll(
          HBoxBuilder.create().spacing(10).children(stroke, effect).build(),
          HBoxBuilder.create().spacing(10).fillHeight(false).children(translate, rotate, scale).build()
        VBox layout = new VBox();
        VBox.setVgrow(scrollPane, Priority.ALWAYS);
        layout.getChildren().addAll(scrollPane, controlPane);
        // show the scene.
        final Scene scene = new Scene(layout, 300, 300);
        stage.setScene(scene);
        stage.show();
        reportBounds(square);
      /** output the squares bounds. */
      private void reportBounds(final Node n) {
        StringBuilder description = new StringBuilder();
        if (stroke.isSelected())       description.append("Stroke 10 : ");
        if (effect.isSelected())       description.append("Dropshadow Effect : ");
        if (translate.isSelected())    description.append("Translated 100, 60 : ");
        if (rotate.isSelected())       description.append("Rotated 45 degrees : ");
        if (scale.isSelected())        description.append("Scale 2 : ");
        if (description.length() == 0) description.append("Unchanged : ");
        System.out.println(description.toString());
        System.out.println("Layout Bounds:    " + n.getLayoutBounds());
        System.out.println("Bounds In Local:  " + n.getBoundsInLocal());
        System.out.println("Bounds In Parent: " + n.getBoundsInParent());
        System.out.println();
    }

  • Turn off scroll pane component pt2

    hello kglad
    sorry, responded by email and it left off message. i guess my answer would be by code, but dragged from component panel. one unprofessional, uneducated workaround was putting a black box behind the text/graphics in other frames so it would cover up the scroll pane that doesn't go away.
    on previous thread you asked...
    are you adding your scrollpane with code?  if yes, remove it (removeChild, remove listeners and null it) with code.  if no, add an empty keyframe in the scollpane's layer after the keyframe where it's added.
    below is the code followed by what's resulting after clicking the "next" button

    attached to your next listener use:
    removeChild(sp);
    sp=null;

  • Keeping focus in the viewable window of a scroll pane

    I have many text fields and text areas inside a scroll pane. When I use tab to cycle through these boxes the focus goes out of the viewable window rather then the scroll pane moving to follow the focus. Is it possible for the scroll pane to follow the focus? I would think it is. But I haven't been able to figure out how. Any ideas?
    Thanks,
    Mark

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class test extends JFrame {
      FieldListener fieldListener = new FieldListener();
      final static int fieldNumber = 15;
      JPanel panel;
      public test() {
        super("Focused Scrolling");
        panel = new JPanel();
        panel.setLayout(new GridLayout(0,1));
        JTextField textField;
        for(int i = 0; i < fieldNumber; i++) {
          textField  = new JTextField("TextField # " + i);
          textField.addFocusListener(fieldListener);
          panel.add(textField);
        JScrollPane scrollPane = new JScrollPane(panel);
        getContentPane().add(scrollPane, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,200);
        setLocation(350,200);
        setVisible(true);
      class FieldListener extends FocusAdapter {
        public void focusGained(FocusEvent e) {
          JComponent field = (JComponent)e.getSource();
          Rectangle r = field.getBounds();
          //System.out.println("r = " + r);
          // JComponent method sends message to component's
          // parent who implements scrollable interface
          panel.scrollRectToVisible(r);
      public static void main(String[] args) {
        new test();
    }

  • Setting scroll pane initial display size

    hello.
    how can i modify the modified code below so that users of my video library system would be able to view CD/DVD/Game information by name, age category, type and year? the text area is not displaying in a proper size - i have to use the scroll pane to view the data in the text area. i should be able to view the data in the text area without a scrollpane because there is not much data in the database. how can i make the text area bigger?
    thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class ViewProductDetails extends JFrame{
       JPanel pnlBox, pnlBody, pnlFooter; 
       JCheckBox name;
       JCheckBox ageCategory;
       JCheckBox type;
       JCheckBox year;
       JButton returnToProductMenu;
       JTextArea jta;
       Container contentpane;
       Connection db;
       Statement statement;
       public void makeConnection(){
          try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch(Exception e){
               System.out.println("Problem loading the driver");
       public void setHostURL(){
          String url = "jdbc:odbc:VideoLibrary";
          closeDB();
          try{
             db = DriverManager.getConnection(url,"","");
             statement = db.createStatement();
             DatabaseMetaData dbmd = db.getMetaData();
             ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"});
          catch(Exception e){
               System.out.println("Could not initialise the database");
               e.printStackTrace();
       public void selectProductOne(){
          try{
             ResultSet rs1 = statement.executeQuery("SELECT * FROM Product ORDER BY name");
             ResultSetMetaData rsmd1 = rs1.getMetaData();
             for(int i = 1; i <= rsmd1.getColumnCount(); i++){
                jta.append(rsmd1.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs1.next()){
                for(int i = 1; i <= rsmd1.getColumnCount(); i++){
                   jta.append(rs1.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ea){
             ea.printStackTrace();
       public void selectProductTwo(){
          try{
             ResultSet rs2 = statement.executeQuery("SELECT * FROM Product ORDER BY ageCategory");
             ResultSetMetaData rsmd2 = rs2.getMetaData();
             for(int i = 1; i <= rsmd2.getColumnCount(); i++){
                jta.append(rsmd2.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs2.next()){
                for(int i = 1; i <= rsmd2.getColumnCount(); i++){
                   jta.append(rs2.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException eb){
             eb.printStackTrace();
       public void selectProductThree(){
          try{
             ResultSet rs3 = statement.executeQuery("SELECT * FROM Product ORDER BY type");
             ResultSetMetaData rsmd3 = rs3.getMetaData();
             for(int i = 1; i <= rsmd3.getColumnCount(); i++){
                jta.append(rsmd3.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs3.next()){
                for(int i = 1; i <= rsmd3.getColumnCount(); i++){
                   jta.append(rs3.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ec){
             ec.printStackTrace();
       public void selectProductFour(){
          try{
             ResultSet rs4 = statement.executeQuery("SELECT * FROM Product ORDER BY year");
             ResultSetMetaData rsmd4 = rs4.getMetaData();
             for(int i = 1; i <= rsmd4.getColumnCount(); i++){
                jta.append(rsmd4.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs4.next()){
                for(int i = 1; i <= rsmd4.getColumnCount(); i++){
                   jta.append(rs4.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ed){
             ed.printStackTrace();
       public void closeDB(){
          try{
             if(statement != null){
                statement.close();
             if(db != null){
                db.close();
          catch(Exception e){
             System.out.println("Could not close the current connection");
             e.printStackTrace();
       public ViewProductDetails(){
          super("View Product Details");
          contentpane = getContentPane();
          contentpane.setLayout(new BorderLayout());
          pnlBox = new JPanel();
          pnlBody = new JPanel();
          pnlFooter = new JPanel();
          jta = new JTextArea();
          jta.setFont(new Font("Serif", Font.PLAIN, 12));
          jta.setLineWrap(true);
          jta.setWrapStyleWord(true);
          jta.setEditable(false);
          name = new JCheckBox("Name");
          ageCategory = new JCheckBox("Age Category");
          type = new JCheckBox("Type");
          year = new JCheckBox("Year");
          pnlBox.add(name);
          pnlBox.add(ageCategory);
          pnlBox.add(type);
          pnlBox.add(year);
          JScrollPane jsp = new JScrollPane(jta);
          pnlBody.add(jsp, BorderLayout.CENTER);
          returnToProductMenu = new JButton("Return To Product Menu");
          pnlFooter.add(returnToProductMenu);
          contentpane.add(pnlBox,BorderLayout.NORTH);
          contentpane.add(pnlBody,BorderLayout.CENTER);
          contentpane.add(pnlFooter,BorderLayout.SOUTH);
          pack();
          setLocationRelativeTo(null);
          setVisible(true);
          name.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductOne();
                closeDB();
          ageCategory.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductTwo();
                closeDB();
          type.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductThree();
                closeDB();  
          year.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductFour();
                closeDB();     
          returnToProductMenu.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                setVisible(false);
       public static void main(String[] args){
          new ViewProductDetails();
    }

    hello.
    thanks for the reply. i did what you told me to do. but when i compile the program i get the following error (both error + code are shown below).
    ----jGRASP exec: javac -g E:\CP4B Project\ViewProductDetails.java
    ViewProductDetails.java:174: cannot find symbol
    symbol : method setPreferredSize()
    location: class javax.swing.JScrollPane
    jsp.setPreferredSize();
    ^
    1 error
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class ViewProductDetails extends JFrame{
       JPanel pnlBox, pnlBody, pnlFooter; 
       JCheckBox name;
       JCheckBox ageCategory;
       JCheckBox type;
       JCheckBox year;
       JButton returnToProductMenu;
       JTextArea jta;
       Container contentpane;
       Connection db;
       Statement statement;
       public void makeConnection(){
          try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch(Exception e){
               System.out.println("Problem loading the driver");
       public void setHostURL(){
          String url = "jdbc:odbc:VideoLibrary";
          closeDB();
          try{
             db = DriverManager.getConnection(url,"","");
             statement = db.createStatement();
             DatabaseMetaData dbmd = db.getMetaData();
             ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"});
          catch(Exception e){
               System.out.println("Could not initialise the database");
               e.printStackTrace();
       public void selectProductOne(){
          try{
             ResultSet rs1 = statement.executeQuery("SELECT * FROM Product ORDER BY name");
             ResultSetMetaData rsmd1 = rs1.getMetaData();
             for(int i = 1; i <= rsmd1.getColumnCount(); i++){
                jta.append(rsmd1.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs1.next()){
                for(int i = 1; i <= rsmd1.getColumnCount(); i++){
                   jta.append(rs1.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ea){
             ea.printStackTrace();
       public void selectProductTwo(){
          try{
             ResultSet rs2 = statement.executeQuery("SELECT * FROM Product ORDER BY ageCategory");
             ResultSetMetaData rsmd2 = rs2.getMetaData();
             for(int i = 1; i <= rsmd2.getColumnCount(); i++){
                jta.append(rsmd2.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs2.next()){
                for(int i = 1; i <= rsmd2.getColumnCount(); i++){
                   jta.append(rs2.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException eb){
             eb.printStackTrace();
       public void selectProductThree(){
          try{
             ResultSet rs3 = statement.executeQuery("SELECT * FROM Product ORDER BY type");
             ResultSetMetaData rsmd3 = rs3.getMetaData();
             for(int i = 1; i <= rsmd3.getColumnCount(); i++){
                jta.append(rsmd3.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs3.next()){
                for(int i = 1; i <= rsmd3.getColumnCount(); i++){
                   jta.append(rs3.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ec){
             ec.printStackTrace();
       public void selectProductFour(){
          try{
             ResultSet rs4 = statement.executeQuery("SELECT * FROM Product ORDER BY year");
             ResultSetMetaData rsmd4 = rs4.getMetaData();
             for(int i = 1; i <= rsmd4.getColumnCount(); i++){
                jta.append(rsmd4.getColumnName(i) + "    ");
             jta.append("\n");
             while(rs4.next()){
                for(int i = 1; i <= rsmd4.getColumnCount(); i++){
                   jta.append(rs4.getObject(i) + "     ");
                jta.append("\n");
          catch(SQLException ed){
             ed.printStackTrace();
       public void closeDB(){
          try{
             if(statement != null){
                statement.close();
             if(db != null){
                db.close();
          catch(Exception e){
             System.out.println("Could not close the current connection");
             e.printStackTrace();
       public ViewProductDetails(){
          super("View Product Details");
          contentpane = getContentPane();
          contentpane.setLayout(new BorderLayout());
          pnlBox = new JPanel();
          pnlBody = new JPanel();
          pnlFooter = new JPanel();
          jta = new JTextArea();
          jta.setFont(new Font("Serif", Font.PLAIN, 12));
          jta.setLineWrap(true);
          jta.setWrapStyleWord(true);
          jta.setEditable(false);
          name = new JCheckBox("Name");
          ageCategory = new JCheckBox("Age Category");
          type = new JCheckBox("Type");
          year = new JCheckBox("Year");
          pnlBox.add(name);
          pnlBox.add(ageCategory);
          pnlBox.add(type);
          pnlBox.add(year);
          JScrollPane jsp = new JScrollPane(jta);
          jsp.setPreferredSize();
          pnlBody.add(jsp, BorderLayout.CENTER);
          returnToProductMenu = new JButton("Return To Product Menu");
          pnlFooter.add(returnToProductMenu);
          contentpane.add(pnlBox,BorderLayout.NORTH);
          contentpane.add(pnlBody,BorderLayout.CENTER);
          contentpane.add(pnlFooter,BorderLayout.SOUTH);
          pack();
          setLocationRelativeTo(null);
          setVisible(true);
          name.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductOne();
                closeDB();
          ageCategory.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductTwo();
                closeDB();
          type.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductThree();
                closeDB();  
          year.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                makeConnection();
                setHostURL();
                selectProductFour();
                closeDB();     
          returnToProductMenu.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
                setVisible(false);
       public static void main(String[] args){
          new ViewProductDetails();
    }

Maybe you are looking for