I have the following problem:
I have a GridBagLayout, in which 3 columns are present and a variable number of rows.
The rows all have corresponding data, so each row should be aligned with eachother.
The nasty thing now comes in: each grid cell of the third column consists of a JPanel that
increases in size horizontally over time. So, these panels become larger than the column
width. So, I made a JScrollPane inside the main panel, which contains another JPanel with
another GridBagLayout. This, however, seems to be impossible to align with the original
gridbag. This obviously makes sense, since it is fundamentally a counterintuitive idea to
create a second GridBagLayout, inside the JScrollPane.
So, basically, my question is the following: Is it possible to create a scrollable area within
a GridBagLayout, such that I can keep adding components to the GridBag, within the
scrollable area?
I made a short piece of code that might be illustrating.
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
MyPanel panel = new MyPanel();
c.weightx = 0.0;
c.ipady = 30;
for(int i = 0; i<15; i++){
panel = new MyPanel();
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = i;
c.ipadx = 500;
c.gridwidth = 1;
pane.add(panel, c);
panel = new MyPanel();
c.gridx = 1;
c.gridy = i;
c.ipadx = 100;
pane.add(panel,c);
}
JPanel tracePanel = new JPanel(new GridBagLayout());
for(int i=0; i<15; i++){
panel = new MyPanel();
panel.setPreferredSize(new Dimension(100,12));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = i;
c.ipadx = 100;
tracePanel.add(panel,c);
}
JScrollPane sp = new JScrollPane(tracePanel);
c.gridx = 2;
c.gridy = 0;
c.gridheight = 15;
c.fill = GridBagConstraints.BOTH;
pane.add(sp,c);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
....and MyPanel.java :
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
class MyPanel extends JPanel {
MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
}