Skip to main content

Problem with JScrollPane containing Jpanel

1 reply [Last post]
bjornvanden
Offline
Joined: 2010-05-06
Points: 0

I have a JScrollpane containing a Panel with 100 TextFields (in a GridBagLayout). I see the panel in my frame and also the scrollbars. But when I scroll everything that was not in the window doesn't appear I only see a gray window...
here is my code:
import java.awt.*;
import javax.swing.*;
class ScrollDesktop extends JDesktopPane implements Scrollable {
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}

public int getScrollableUnitIncrement(Rectangle r, int axis, int dir) {
return 100;
}

public int getScrollableBlockIncrement(Rectangle r, int axis, int dir) {
return 100;
}

public boolean getScrollableTracksViewportWidth() {
return true;
}

public boolean getScrollableTracksViewportHeight() {
return true;
}
}

public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
c.gridx=0;
c.gridy=0;
for (int i=0;i<100;i++){
c.gridx=0;
p.add(new Label(i+""),c);
c.gridx=1;
p.add(new TextField(10),c);
c.gridy++;
}
p.setPreferredSize(new Dimension(50,2500));
JScrollPane pane=new JScrollPane();
pane.setSize(50,300);
pane.getViewport().add(p);
//pane.setBounds(0,0,50,2500);

getContentPane().add(pane, "Center");
setSize(300, 300);
setVisible(true);
}

public static void main(String arg[]) {
new Main();
}
}

Thanks

Message was edited by: bjornvanden

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17
Points: 0

Please post code between [ code ] // code here [ /code ] tags without spaces.

Don't mix AWT and Swing - use JLabel and JTextField.

Don't use setSize, this is set by the layout manager. Typically you also shouldn't setPreferredSize, since this is calculated by the layout manager.

In a simple example, I don't get a gray window:

[code]import java.awt.*;
import javax.swing.*;

public class HundredFields {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
for (int i = 0; i < 100; i++) {
c.gridx = 0;
panel.add(new JLabel(i + ""), c);
c.gridx = 1;
panel.add(new JTextField(10), c);
c.gridy++;
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(panel));
// a better choice would be to let the panel implement Scrollable
// and calculate a preferred scrollable size of say ten fields high
frame.setPreferredSize(new Dimension(400, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
[/code]