Panel in ScrollPane!!!

What I want is the following: If I enlarge my Panel(Dimension) , I want my scrollbar to adjust so I can scroll left and and right to see the whole Panel in the ScrollPane. I can see my scroller but the will not change So I can see the whole Panel.
Here's my code.
class Grafiekxt extends Panel implements Observer{
int breedte,hoogte,ymultiplier;
double ynul;
Vector vect = new Vector();
int counter;
int x;
int y;
Populatie p;
Grafiekxt(int breedte,int hoogte){
setLayout(null);
this.breedte=breedte-3;
this.hoogte=hoogte-5;
this.x = breedte;
this.y = hoogte;
ynul=this.hoogte/2.0;
public Dimension getPreferredSize() {
if(p!=null){
          if((p.getXteller()*20)>breedte){
          x = p.getXteller()*20;
     return new Dimension(x,y);
public void update(Observable obs, Object arg){
p = (Populatie) obs;
if(p.getXteller()==1){
          vect.clear();
     Double fw = new Double((p.getFunctiewaarde(p.indexVanBesteIndividu())));
vect.add(fw);
repaint();
public double bestOf(){
     // de methode zal de grootste absolute double retourneren die in de vector zitten.
     double best = Math.abs(((Double)vect.elementAt(0)).doubleValue());
     for(int i = 0;i < vect.size();i++){
          if(Math.abs(((Double)vect.elementAt(i)).doubleValue())>best){
               best =      Math.abs(((Double)vect.elementAt(i)).doubleValue());
     return best;
public void paint(Graphics g){
     g.setColor(Color.white);
     g.drawLine(0,0,0,hoogte);
     if(p!=null){
          ymultiplier = (int)(ynul/bestOf());
          for(int i = 0; i < p.getXteller(); i++){
               if((i*20) > breedte){
                    breedte = breedte+(i*20);
                    x = breedte;
               g.drawLine(0,(int)ynul,breedte,(int)ynul);
               g.drawLine((i+1)*20, (int)(ynul+2), (i+1)*20, (int)(ynul-2));
               g.drawString(""+i, (i+1)*20, (int)(ynul-2));
               g.drawRect((i+1)*20,(int)(ynul-(((Double)vect.elementAt(i)).doubleValue())*ymultiplier) , 1, 1);     
}

Anybody, please

Similar Messages

  • How to scroll panels using scrollpane?

    i am having two panels containing different images in a main panel.
    my problem is that due to big size only one panel is visible in run time so i want to add scrollbar to the main panel.
    i have used scrollpane for the main panel but i am getting confused that at which event i should put the code of repainting the visible area.
    can anybody tell me how to implement this.
    plz... help

    gaurav_mishra wrote:
    actually i am working in netbeans so i don't know where is the paint method of the panel.can anybody plz help me get rid of this problemApparently we were all mistaken by your description, it looked like you were writing a custom JPanel subclass, with a custom paintComponent() method that would draw the images...
    I don't know how you display images in a Panel with NetBeans, but presumably it re-uses some existing JComponent and it doesn't have to generate a paintComponent() method.
    At that step you should consider the very first reply: please post some code, the shortest running example that demonstrates your problem.
    If you're reluctant, try a simple scroll example: put a single JButton in a JPanel with a FlowLayout, using an image as the button's icon. Stuff this panel into a JScrollPane, itslef in a JFrame, run the app and resize the JFrame. Check whether the button displays appropriately. If it does, try to check what's different with your problematic case.
    I like NetBeans (or merely, NetBeans's GUI designer), but it's not the best way to learn Swing programming, which looks like what you're doing.

  • How to make the panel with scrollpane transparent?

    Thanks Camicker for your help, it solves the problem but i got a new problem i.e. i want to make that panel with scrollbar transparent for this i have tried setOpaqe(false) for both scrollpane and panel but it doesn't work. do u have any solution?

    I think camickr (not Camicker) already told you to set the opacity of the JScrollPane's viewport.
    Spend just a few minutes with the JScrollPane API and you'll find an exploded view showing the components that make up a scroll pane.
    db

  • Adding panels to scrollpane

    I want to include panels dynamically into the scroll pane. Which layout should I select for this ? I read that for scroll panes, only ScrollPaneLayout can be used, but it does not work for my application. Can anyone tell me please how do I add the panels to it ? The code I m using is as follows:
    jScrollPaneMain.setLayout(new ScrollPaneLayout());
    jScrollPaneMain.add(jPanel1);
    jScrollPaneMain.revalidate();
    jScrollPaneMain.repaint(); 

    Make an intermediate panel:
    JPanel intermediate = new JPanel();
    scrollPane.setViewportView(intermediate);and then:
    intermediate.add(panel1);
    intermediate.add(panel2);The layout for the intermediate panel could be a GridLayout, GridBagLayout or a GroupLayout. Depending on how the added panels have to behave.

  • Refresh the Panel or Scrollpane in a frame?

    When I open a frame the panel in the scrollpane is transparant . but if you scroll it will fill with the color I gave. It will also fill if I minimalize and then maximalize.
    I tried validate, update , repaint

    Hey, well I've had the same question. repaint() doesn't seem to work. Anyway, I've found a trick that works sometimes.
    JPanel oustidePane = new JPanel(new BorderLayout());
    JPanel labelPane = new JPanel();
    label = new JLabel(" ");
    label.setPreferredSize(new Dimension(10,10));
    //or smaller, i actually didn't set a size
    labelPane.add(label);
    outsidePane.add(labelPane, BorderLayout.SOUTH)
    ousidePanel.add(yourPanelorScrollPanel, BorderLayout.CENTER);
    //put this somewhere where you can access label from
    //other ods
    JLabel label;
    then add this ousidePanel where you would have added your panel.
    when you want to refresh your window, try something like this:
    void refresh()
    if(label.getText() == " ")
    label.setText(" "); //two spaces this time
    else
    label.setText(" "); // back to one space
    let me know if this works for you

  • Adding panel to scrollpane on button click

    Please run the below code with
    javac MyTestingNew.java and
    java MyTestingNew
    I am having a button(ADD ME) on click of that I want to add panel containg textfield
    which will append to already exist textfields which are diasplyed in jscrollpane
    How I can proceed??
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.event.*;
    class MyTestingNew extends JFrame{
         static Sale2 sale2;
         static int coordinate = 0;
         final int SIZE = 5;
           JPanel[] jp = new JPanel[20];
       //     ButtonGroup[] group = new ButtonGroup[SIZE]; 
       //     JRadioButton[] rb = new JRadioButton[SIZE * SIZE];
         JTextField[] jtf = new JTextField[SIZE * 1000];
         JButton jb = new JButton();
            public MyTestingNew(){
                 buildGUI(); 
        public void buildGUI(){   
             setSize(1200,800);   
             //setLocation(400,300);  
              setDefaultCloseOperation(EXIT_ON_CLOSE);  
              JPanel main = new JPanel();
             //JPanel main = new JPanel(new GridLayout(20,1));
             main.setLayout(null);
             jb.setText("ADD ME");
             jb.setBounds(0,0,100,30);
             sale2=new Sale2(this);
             jb.addActionListener(sale2);
             main.setPreferredSize(new Dimension(353,800));
             //main.setBounds(420,335,353,381);
             //main.setBounds(0,0,353,381);
             for(int x = 0; x <20; x++){
                   //group[x] = new ButtonGroup();    
                jp[x] = new JPanel();
                    //jp[x] = new JPanel(new GridLayout(1,SIZE));
                  jp[x].setLayout(null);
                  jp[x].setBounds(0,coordinate,353,32);
                  //jp[x].setBounds(0,coordinate,353,32);
                    System.out.println("SIZE  :"+ SIZE);
                jp[x].setBorder(BorderFactory.createEtchedBorder());   
                for(int y = 1; y < SIZE+1; y++){
                     int rbNum = x*SIZE + y;
                     System.out.println("X : "+x+ "Y : "+y+" rbNum : "+rbNum);
                     if(y==1) {jtf[rbNum] = new JTextField(""+rbNum);jtf[rbNum].setBounds(0,0,30,32);}
                     if(y==2) {jtf[rbNum] = new JTextField(""+rbNum);jtf[rbNum].setBounds(32,0,180,32);}
                     if(y==3) {jtf[rbNum] = new JTextField(""+rbNum);jtf[rbNum].setBounds(214,0,35,32);}
                     if(y==4) {jtf[rbNum] = new JTextField(""+rbNum);jtf[rbNum].setBounds(251,0,35,32);}
                     if(y==5) {jtf[rbNum] = new JTextField(""+rbNum);jtf[rbNum].setBounds(288,0,65,32);}
                    jp[x].add(jtf[rbNum]);  
                     coordinate = coordinate + 7;
                main.add(jp[x]);   
            JScrollPane sp = new JScrollPane(main);
             //sp.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
             sp.setBounds(420,335,353,350);
             JPanel main2 = new JPanel();
             main2.setLayout(null);
             //main2.setPreferredSize(new Dimension(400,400));
             main2.add(sp);
             main2.add(jb);
             getContentPane().add(main2);
           public static void main(String[] args){
                   new MyTestingNew().setVisible(true);
    class Sale2 implements ActionListener
    MyTestingNew parent;
    Sale2(MyTestingNew parent)
    this.parent=parent;
    public void actionPerformed(ActionEvent e)
         //My code will come here
         System.out.println("get from button");
    }

    You really should start learning how to use LayoutManagers.. they make life a lot easier
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class MyTestingNew extends JFrame {
        final int SIZE = 5;
        JPanel[] jp = new JPanel[20];
        JTextField[] jtf = new JTextField[SIZE * 1000];
        JButton jb = new JButton();
        private int nrOfRows = 20;//starting nr of rows
        public MyTestingNew() {
            buildGUI();
        public void buildGUI() {
            setTitle("My Test");
            setSize(1200, 800);
            //setLocation(400,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            final JPanel main = new JPanel();
            //JPanel main = new JPanel(new GridLayout(20,1));
            main.setLayout(new BoxLayout(main,BoxLayout.Y_AXIS));
            jb.setText("ADD ME");
            jb.setBounds(0, 0, 100, 30);
            jb.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt){
                    JPanel newPanel = new JPanel();
                    newPanel.setLayout(new GridLayout(1,SIZE));
                    for (int y = 1; y < SIZE + 1; y++) {
                        int rbNum = nrOfRows * SIZE + y;
                        System.out.println("X : " + nrOfRows + " Y : " + y + " rbNum : " + rbNum);
                        newPanel.add(new JTextField("" + rbNum));
                    main.add(newPanel);
                    main.revalidate();
                    nrOfRows++;//added a new row
            for (int x = 0; x < nrOfRows; x++) {
                jp[x] = new JPanel();
                jp[x].setLayout(new GridLayout(1,SIZE));
                System.out.println("SIZE  :" + SIZE);
                for (int y = 1; y < SIZE + 1; y++) {
                    int rbNum = x * SIZE + y;
                    System.out.println("X : " + x + " Y : " + y + " rbNum : " + rbNum);
                    jtf[rbNum] = new JTextField("" + rbNum);
                    jp[x].add(jtf[rbNum]);
                main.add(jp[x]);
            JScrollPane sp = new JScrollPane(main);
            //sp.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            sp.setBounds(420, 335, 353, 350);
            JPanel main2 = new JPanel();
            main2.setLayout(null);
            //main2.setPreferredSize(new Dimension(400,400));
            main2.add(sp);
            main2.add(jb);
            getContentPane().add(main2);
        public static void main(String[] args) {
            new MyTestingNew().setVisible(true);
    }

  • Design problem(split pane scrollpane Insets)

    hi,
    doing a exam simulator prgm
    design is like,
    Question (text area with scrollpane)
    Answers (checkbox inside panel with scrollpane)
    used split pane between qst and ans but big thick bar comes how to reduce size and it is not
    moving.
    used GridLayout for container and panel.
    PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
    same prblm for checkbox they to appear extreme left on screen.

    Put those components in a JPanel overwriting the getInsets() method like this:
    JPanel cPane=new JPanel(){
        private final Insets _insets=new Insets(10,10,10,10);
        public Insets getInsets(){
            return _insets;
    };...should do the trick, take a look at the Insets class if you need information on how defining it...

  • How to restrict the maximum size of a java.awt.ScrollPane

    Dear all,
    I would like to implement a scroll pane which is resizable, but not to a size exceeding the maximum size of the java.awt.Canvas that it contains.
    I've sort of managed to do this by writing a subclass of java.awt.ScrollPane which implements java.awt.event.ComponentListener and has a componentResized method that checks whether the ScrollPane's viewport width (height) exceeds the content's preferred size, and if so, resizes the pane appropriately (see code below).
    It seems to me, however, that there ought to be a simpler way to achieve this.
    One slightly weird thing is that when the downsizing of the pane happens, the content can once be moved to the left by sliding the horizontal scrollbar, but not by clicking on the arrows. This causes one column of gray pixels to disappear and the rightmost column of the content to appear; subsequent actions on the scrollbar does not have any further effect. Likewise, the vertical scrollbar can also be moved up once.
    Also, I would like a java.awt.Frame containing such a restrictedly resizable scrollpane, such that the Frame cannot be resized by the user such that its inside is larger than the maximum size of the scrollpane. The difficulty I encountered with that is that setSize on a Frame appears to set the size of the window including the decorations provided by the window manager (fvwm2, if that matters), and I haven't been able to find anything similar to getViewportSize, which would let me find out the size of the area inside the Frame which is available for the scrollpane which the frame contains.
    Thanks in advance for hints and advice.
    Here's the code of the componentResized method:
      public void componentResized(java.awt.event.ComponentEvent e)
        java.awt.Dimension contentSize = this.content.getPreferredSize();
        this.content.setSize(contentSize);
        java.awt.Dimension viewportSize = getViewportSize();
        System.err.println("MaxSizeScrollPane: contentSize = " + contentSize);
        System.err.println("MaxSizeScrollPane: viewportSize = " + viewportSize);
        int dx = Math.max(0, (int) (viewportSize.getWidth() - contentSize.getWidth()));
        int dy = Math.max(0, (int) (viewportSize.getHeight() - contentSize.getHeight()));
        System.err.println("MaxSizeScrollPane: dx = " + dx + ", dy = " + dy);
        if ((dx > 0) || (dy > 0))
          java.awt.Dimension currentSize = getSize();
          System.err.println("MaxSizeScrollPane: currentSize = " + currentSize);
          setSize(new java.awt.Dimension(((int) currentSize.getWidth()) - dx, ((int) currentSize.getHeight()) - dy));
        System.err.println();
      }Best regards, Jan

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class ScrollPaneTest
        GraphicCanvas canvas;
        CustomScrollPane scrollPane;
        private Panel getScrollPanel()
            canvas = new GraphicCanvas();
            scrollPane = new CustomScrollPane();
            scrollPane.add(canvas);
            // GridBagLayout allows scrollPane to remain at
            // its preferred size during resizing activity
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            panel.add(scrollPane, gbc);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        private Panel getUIPanel()
            int w = canvas.width;
            int h = canvas.height;
            int visible = 100;
            int minimum = 200;
            int maximum = 500;
            final Scrollbar
                width  = new Scrollbar(Scrollbar.HORIZONTAL, w,
                                       visible, minimum, maximum),
                height = new Scrollbar(Scrollbar.HORIZONTAL, h,
                                       visible, minimum, maximum);
            AdjustmentListener l = new AdjustmentListener()
                public void adjustmentValueChanged(AdjustmentEvent e)
                    Scrollbar scrollbar = (Scrollbar)e.getSource();
                    int value = scrollbar.getValue();
                    if(scrollbar == width)
                        canvas.setWidth(value);
                    if(scrollbar == height)
                        canvas.setHeight(value);
                    canvas.invalidate();
                    scrollPane.validate();
            width.addAdjustmentListener(l);
            height.addAdjustmentListener(l);
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents(new Label("width"),  width,  panel, gbc);
            addComponents(new Label("height"), height, panel, gbc);
            gbc.anchor = GridBagConstraints.CENTER;
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        public static void main(String[] args)
            ScrollPaneTest test = new ScrollPaneTest();
            Frame f = new Frame();
            f.addWindowListener(test.closer);
            f.add(test.getScrollPanel());
            f.add(test.getUIPanel(), "South");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
            f.addComponentListener(new FrameSizer(f));
    class GraphicCanvas extends Canvas
        int width, height;
        public GraphicCanvas()
            width = 300;
            height = 300;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int dia = Math.min(width, height)*7/8;
            g2.setPaint(Color.blue);
            g2.draw(new Rectangle2D.Double(width/16, height/16, width*7/8, height*7/8));
            g2.setPaint(Color.green.darker());
            g2.draw(new Ellipse2D.Double(width/2 - dia/2, height/2 - dia/2, dia-1, dia-1));
            g2.setPaint(Color.red);
            g2.draw(new Line2D.Double(width/16, height*15/16-1, width*15/16-1, height/16));
        public Dimension getPreferredSize()
            return new Dimension(width, height);
        public Dimension getMaximumSize()
            return getPreferredSize();
        public void setWidth(int w)
            width = w;
            repaint();
        public void setHeight(int h)
            height = h;
            repaint();
    class CustomScrollPane extends ScrollPane
        Dimension minimumSize;
        public Dimension getPreferredSize()
            Component child = getComponent(0);
            if(child != null)
                Dimension d = child.getPreferredSize();
                if(minimumSize == null)
                    minimumSize = (Dimension)d.clone();
                Insets insets = getInsets();
                d.width  += insets.left + insets.right;
                d.height += insets.top + insets.bottom;
                return d;
            return null;
        public Dimension getMinimumSize()
            return minimumSize;
        public Dimension getMaximumSize()
            Component child = getComponent(0);
            if(child != null)
                return child.getMaximumSize();
            return null;
    class FrameSizer extends ComponentAdapter
        Frame f;
        public FrameSizer(Frame f)
            this.f = f;
        public void componentResized(ComponentEvent e)
            Dimension needed = getSizeForViewport();
            Dimension size = f.getSize();
            if(size.width > needed.width || size.height > needed.height)
                f.setSize(needed);
                f.pack();
         * returns the minimum required frame size that will allow
         * the scrollPane to be displayed at its preferred size
        private Dimension getSizeForViewport()
            ScrollPane scrollPane = getScrollPane(f);
            Insets insets = f.getInsets();
            int w = scrollPane.getWidth() + insets.left + insets.right;
            int h = getHeightOfChildren() + insets.top + insets.bottom;
            return new Dimension(w, h);
        private ScrollPane getScrollPane(Container cont)
            Component[] c = cont.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] instanceof ScrollPane)
                    return (ScrollPane)c[j];
                if(((Container)c[j]).getComponentCount() > 0)
                    return getScrollPane((Container)c[j]);
            return null;
        private int getHeightOfChildren()
            Component[] c = f.getComponents();
            int extraHeight = 0;
            for(int j = 0; j < c.length; j++)
                int height;
                if(((Container)c[j]).getComponent(0) instanceof ScrollPane)
                    height = ((Container)c[j]).getComponent(0).getHeight();
                else
                    height = c[j].getHeight();
                extraHeight += height;
            return extraHeight;
    }

  • ScrollPane Problem breaking my heart...

    HI .I Want to read in a number from a textfield.This number will decide how many textfileds will appear on a panel. I want to then add this panel to a ScrollPane.I have this working but when the panel is in the scrollPane it doesnt scroll down the full length of the panel
    heres my code structure
    Create Scrollpane
    Read integer
    Create panel with textFields
    Add Panel to Scrollpane
    Add ScrollPane
    Is this the wrong way.....
    Any help really appreciated

    The client area of a ScrollPane is sized according to the components preferred size. The return value of the panels getPreferredSize is interesting. Does it have the value you expect?
    public Dimension getPreferredSize()
         Dimension dim;
         dim=super.getPreferredSize();
         System.out.println(�Preferre size:�+dim.width+�, �+dim.height);
         Return dim;
    }The other possible problem is the validation. When is the layout performed?
    public void doLayout()
         System.out.println(�doLayout() called�);
    }Try to add the above two methods to your panel class.
    Ragnvald.

  • Scrollpane remains big!

    hi guys
    I have my JFrame, and the contentpane has xPanel on left hand side and a JScrollPane in centre. The JScrollpane contains yPanel, and yPanel is cardLayout.
    JFrame's size is set to be half the width and height.
    xPanel contains buttons, that do SQL queries, and the result of the SQl query returned is put inside JButtons as text and these JButtons are put inside yPanel.
    If 1 row is returned, we only add 1 button to xPanel. No scrollbars appear, obviously, as they dont need to for one button only.
    If 100 rows are returned from SQL query, yPanel will contain 100 buttons in a column. So the ScrollPane bars come, which is correct , so that we can scroll up and down.
    The problem is:
    If the next query returned 1 row again, the ScrollPane is still the big size! The scrollbars are still there even though we dont need them as we only have one JButton in the yPanel now.
    How can we sort this out please?
    Thanks.

    The JScrollpane contains yPanel, and yPanel iscardLayout.
    I would do it the other way around. Add the panel and
    scrollPane to the CardLayout. That is replace the
    scrollPane in the CardLayout everytime, not the panel.Thank you.

  • Adding Buttons to a ScrollPane??

    Hello Swing people,
    I have had this problem now for quite some time and still have had no luck in getting it right. I am coding an ordering system and on this form is a Jtable displaying product details. Beside the Jtable are category buttons one after the other in a vertical line and there are 18 of them - meaning they cannot fit on the screen!! Therefore i want these buttons to be in some kind of scollpane or list so they can all be viewed.
    I thought this would be a simple matter of adding buttons to a scrollpane and then to the panel but this has proved not the case! Does anyone know how i could do this as i have been trying this for too long without the help of you geniuses???
    To give u an idea of what i was trying here is a snippet of my code:
    import javax.swing.*;
    public class junk2 extends JFrame{
         junk2()    {
         JPanel panel = new JPanel();
         panel.setLayout(new java.awt.GridLayout(0, 1) );
         JButton []button = new JButton[20];
         for(int i=0; i<button.length; i++) {
              button=new JButton(""+(i+1) );
              panel.add(button[i]);
         JScrollPane scroll = new JScrollPane(panel);
         getContentPane().add(scroll, java.awt.BorderLayout.CENTER);
         setSize(50, 100);
         setDefaultCloseOperation( EXIT_ON_CLOSE );
         public static void main(String []args) {
              new junk2().show();
    This code is fine and puts buttons in a vertical line but the buttons only have numbers on them from 1-20, i want the names of the buttons i have declared to be in here - therefore allowing the action performed on these buttons to be recognised and therefore work too! - anyone know how to get around this??
    Also the scrollpane with these buttons in apears in a whole new frame being that it is a small test program but does anyone know how to ensure the buttons appear in the scrollpane only and not in a new frame??
    all 25 dukes if someone can sort this long problem out!!!

    Hi guys thanks a lot for your replies, i compiled both of them and they are fine! the first reply is more what i am looking for but there is still a problem, i am finding it difficult to incorporate this piece of code into my order form class.
    Im trying to take out the current declarations of my JButtons and replace it with the code i was given (reply 1) and obviously keep my action performed methods there as they will be the same but cant seem to do this!
    If anyone can add in the code from reply 1 into my code below or at least help me i will give u the 25 dukes, taking into consideration i still want the form (panel) to be displayed as well as the panel or scrollpane containing the JButtons???
    Can u help - cheers in advance!!
    Pc
    public class OrderForm extends JFrame implements ActionListener {
         private JPanel panel;
         private JButton saveArchive,unCompleted,submitOrder,checkSheet,clear,exit,bread,fruit,dairy,
    salads,cakes,frozen,meat,cheeses,sauces,dry,drinks,soup,cleaning,boxes,cups,cutlery,lids,misc,stick,soup2;
         private JScrollPane pane;
         private JTextField textorderno,textorderdate,textdelivdate,textemp,textshop,textsupp;
         private JLabel heading1,heading2,orderno,orderdate,delivdate,emp,shop,supplier;
         private String todaysDate, deliveryDate;
         private ResultSet result;
         private ResultSet shops;
         private int column_count;
         private JComboBox combobox;
         ResultSetTableModel model = new ResultSetTableModel();
         Result rs = new Result(); 
         Orders orderSaving = new Orders();
         ProductOrders tableSaving = new ProductOrders();
         private boolean save;
         JTable table;
         public OrderForm()throws SQLException {
              displayForm();
              displayFields();//Have not provided coz it aint needed for this
              displayButtons();//Wont need this anymore i dont think
              getContentPane().add(panel);
              setVisible(true);
         public void displayForm() throws SQLException{
              setTitle("Pret Ordering System");
              setSize(700,600);
              // Center the frame
              Dimension dim = getToolkit().getScreenSize();
              setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
              //Creates the coloured bored around the panel
              panel = new JPanel();
              panel.setLayout( null );
              Border paneltitled = BorderFactory.createLineBorder(Color.red.darker().darker(),10);
              panel.setBorder(paneltitled);
              ResultSet result = rs.setBreadProds();
              model.fillTableModel(result);
              table = new JTable(model);
              for(int i = 0; i < column_count; i++) {          
                   table.getColumnModel().getColumn (i).setPreferredWidth (200);                   
              table.setSelectionForeground( Color.white );
              table.setSelectionBackground( Color.red.darker().darker() );
              pane = new JScrollPane(table);
                  pane.setBounds(190, 230, 440, 200);
                  panel.add(pane);
              combobox = new JComboBox();
              ResultSet shops = rs.getSupplierNames();
              while(shops.next()){  
                   combobox.addItem(shops.getString("supplier_name"));
    //Hope you can help - cheers

  • Adding Jtree to Panel

    Hi all,
    I have a JTree in a scrollpane rendered with checkbox on each node. I
    When I try adding to JFrame its displaying with scrollbar as expected. like this
    frame.setContentPane(scrollPane); //working fineBut When I try adding to panel and try to display that its not working
    JPanel panel = new JPanel();
    panel.add(scrollPane);
    frame.setContentPane(panel); // displaying tree without scrollbarsthanks,
    sur

    scrollPane.setPreferredSize(new Dimension(x,y));where x,y can be the width/height of the frame

  • ScrollPane Help

    initially i didn't split the panel and data..
    the scrollPane was showing good (table - JTable)...
                table = mainPanel.atmBean.getReturnTable();
                //Set Mode, Border, Size
                table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                table.setBorder(BorderFactory.createEtchedBorder());
                table.setPreferredScrollableViewportSize(mainPanel.getPopupTablePreferredSize());
                //Add table to Scroll Pane
                scrollPane = new JScrollPane(table);
                scrollPane.setPreferredSize(mainPanel.getPopupTablePreferredSize());after splitting the data, i changed like
    add()
    scrollPane = new JScrollPane();
    set()
                table = mainPanel.atmBean.getReturnTable();
                //Set Mode, Border, Size
                table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                table.setBorder(BorderFactory.createEtchedBorder());
                table.setPreferredScrollableViewportSize(mainPanel.getPopupTablePreferredSize());
                //Add table to Scroll Pane
               //THIS IS THE DIFFERENCE
                scrollPane.add(table);
                scrollPane.validate();
                scrollPane.repaint();
               //c is contentPane()
               c.validate();
               c.repaint();
    }the scrollpane doesn't seem to contain the table..

    if i add 1 more panel, the problem gets solved, but wondering why shouldn't the scrollPane work ..
    ie
    add()
      JPanel panel = new JPanel();
    set()
      ..all other steps as shown above
      scrollPane = new JScrollPane(table)
      //one more panel
      panel.removeAll();
      panel.add(scrollPane);
      panel.validate();
      panel.repaint();
    }

  • Help for scrollPane

    hi
    I'm adapting my source code, following the swing tutorial example for scrollbar pane.
    I ask you to check my code because I do not see what I want.
    my code is intended to put a panel on a scrollpane and then add a textfield to the panel.
    the scrollpane is already on my "design" tab (nebeans dev env).
    I do not see this.
    thanks in advance
    testPanel.setEnabled(true);
    testPanel.setBackground(Color.black);
    testPanel.setVisible(true);
    Dimension dimension1=new Dimension(60,60);;
    testPanel.setPreferredSize(dimension1);
    testPanel.setSize(dimension1);
    testPanel.setEnabled(true);
    testPanel.setBackground(new java.awt.Color(0, 0, 0));
    JTextField testTextField=new JTextField("prova");
    testTextField.setEnabled(true);
    testTextField.setBackground(new java.awt.Color(0, 102, 153));
    testPanel.add(testTextField,new org.netbeans.lib.awtextra.AbsoluteConstraints(272, 51, 316, -1));
    JLabel instructionsLeft = new JLabel("Click left mouse button to place a circle.");
    jScrollPane1.add(instructionsLeft);
    jScrollPane1.add(testPanel,new AbsoluteConstraints(140, 10, -1, -1));
    jScrollPane1.setEnabled(true);
    testPanel.repaint();
    jScrollPane1.repaint();
    this.repaint();

    P5music wrote:
    The only hint in the API document section is to use
    jScrollPane1.setViewportView(testPanel);
    Now, I used it instead of jScrollPane1.add(testPanel);
    but nothing changed....It's very hard to guess what you're doing wrong without compilable code. Unless someone very clever comes by soon who can instantly spot your problme, my recommendation that you create and post an SSCCE still stands. In fact odds are, if you create the SSCCE, you'll spot your error and be able to fix it yourself. Much luck.

  • Method all values from row

    Hi,
    Is there a method that get the all the values of a row? I've gone through the java api but didn't found one, but wanted to be sure.
    If not I'll have to do getValueAt for every column?
    Grtz

    Here is one possible implementation using RowTableModel (a self made class).
    To access a row, we can use this: Product product = (Product) model.getRow(rowIndex);
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    public class Tabel extends JPanel {
        private JTable table;
        private JTextField filterText;
        private TableRowSorter<MyTableModel> sorter;
        private String output;
        private final MyTableModel model;
        public Tabel() {
            //Create a table with a sorter.
            model = new MyTableModel();
            sorter = new TableRowSorter<MyTableModel>(model);
            table = new JTable(model);
            table.setRowSorter(sorter);
            table.setPreferredScrollableViewportSize(new Dimension(500, 200));
            table.setFillsViewportHeight(true);
            //Single selection
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            //Making sure columns can't be dragged and dropped
            table.getTableHeader().setReorderingAllowed(false);
            //Double click event
            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent mouseEvent) {
                    if (mouseEvent.getClickCount() == 2) {
                        System.out.print(output);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            JPanel form = new JPanel();
            JLabel l1 = new JLabel("Filter Text:");
            form.add(l1);
            filterText = new JTextField(15);
            //Whenever filterText changes, invoke newFilter.
            filterText.getDocument().addDocumentListener(
                    new DocumentListener() {
                        public void changedUpdate(DocumentEvent e) {
                            newFilter();
                        public void insertUpdate(DocumentEvent e) {
                            newFilter();
                        public void removeUpdate(DocumentEvent e) {
                            newFilter();
            l1.setLabelFor(filterText);
            form.add(filterText);
            add(form);
         * Update the row filter regular expression from the expression in
         * the text box.
        private void newFilter() {
            RowFilter<MyTableModel, Object> rf = null;
            //If current expression doesn't parse, don't update.
            try {
                rf = RowFilter.regexFilter("(?i)" + filterText.getText(), 0); //"(?i)" => Zoeken gebeurd case-insensitive
            } catch (java.util.regex.PatternSyntaxException e) {
                return;
            sorter.setRowFilter(rf);
        class MyTableModel extends RowTableModel {
            private final List<Product> mData;
            private final List<String> cNames;
            public MyTableModel() {
                super(Product.class);
                mData = new ArrayList<Product>();
                mData.add(new Product("Frontline Small", 5, 1));
                mData.add(new Product("Frontline Medium", 10, 2));
                mData.add(new Product("Frontline Large", 15, 1));
                mData.add(new Product("Frontline Extra Large", 20, 2));
                mData.add(new Product("Frontline spuitbus", 7.5, 3));
                cNames = new ArrayList<String>();
                cNames.add("Product");
                cNames.add("Prijs");
                cNames.add("Aantal stuks beschikbaar");
                setDataAndColumnNames(mData, cNames);
                setColumnClass(0, String.class);
                setColumnClass(1, Double.class);
                setColumnClass(2, Integer.class);
            public Object getValueAt(final int rowIndex, final int columnIndex) {
                switch (columnIndex) {
                    case 0:
                        return mData.get(rowIndex).getDescriction();
                    case 1:
                        return mData.get(rowIndex).getPrice();
                    case 2:
                        return mData.get(rowIndex).getNumber();
                return null;
            @Override
            public Class getColumnClass(int column) {
                return super.getColumnClass(column);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Tabel newContentPane = new Tabel();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(final String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class Product {
        private String descriction;
        private double price;
        private int number;
        Product(final String descriction, final double price, final int number) {
            this.descriction = descriction;
            this.price = price;
            this.number = number;
        public String getDescriction() {
            return descriction;
        public void setDescriction(final String descriction) {
            this.descriction = descriction;
        public int getNumber() {
            return number;
        public void setNumber(final int number) {
            this.number = number;
        public double getPrice() {
            return price;
        public void setPrice(final int price) {
            this.price = price;
        @Override
        public String toString() {
            return descriction + ", " + price + ", " + number;
    }

Maybe you are looking for

  • Itunes cant communicate with Ipod

    I bought a new computer, a Toshiba A505 with Windows 7 and downloaded the 64 bit version of Itunes 9.0.3, when I open Itunes, I get a message box that says "the software required to communicate with the Ipod is not installed correctly. Please reinsta

  • IPhone Calendar Didn't Sync

    Does anyone know how to get the iPhone calendar (iCal) to Sync back into the iPhone. I have the original 8 gig phone from June 07, just upgraded the .me account but it only brought in other calendars and not the real one from the iPhone that I had ba

  • Font size in normal reporting

    I'm working on a report where it has to fit a specified page, but using the normal abap reports ( can't use smartforms in this case) , how do I change to font size to smaller size? Thanks, Tarun Kumar

  • Accordion widget content height

    I'm using an accordion widget for the navigation of a site.  Some of the sections have sub-sections and other do not. Is it possible to remove the "content area" of an accordion widget but keep the label?  I tried to set the height of the content are

  • If your BACK UP IS FAILING this could be the answer!

    Thanks to Apple Discussions user scubuhhsteve, my immense TC troubles were finally resolved. Here is the link to his answers: http://discussions.apple.com/message.jspa?messageID=6768215#6768215