Dynamically add JPanel instances to a JScrollPane - java

I'm trying to add precreated JPanel instances into a bigger JPanel into a JScrollPane, but I can't get it to work.
I'm using NetBeans to create the container, then using the context menu to include it into a scroll panel.
To add the JPanel at runtime I'm doing this:
ActivityPanel actPanel;
for(Reservation r: mainFrame.getKiosko().getReservations()) {
if( r.getUser().equals(user)) {
actPanel = new ActivityPanel(r.getActivity(),mainFrame);
actPanel.setHour(r.getHour());
Dimension actDim = new Dimension(600, 100);
actPanel.setPreferredSize(actDim);
actPanel.setMaximumSize(actDim);
actPanel.setMinimumSize(actDim);
pnlReservations.add(actPanel);
}
}
But it just is not working. Should I create the ScrollPanel at runtime? If so How should I do it?
pnlReservation has a BoxLayout by page axis.

actPanel.setPreferredSize(actDim);
Don't try to manually control the preferred size of a component. The size of the panel should be determined by the components you add to the panel.
Same with your pnlReservation, don't hardcode a preferred size. The layout manager will determine its preferred size based on the preferred size of the components added to it.
Then the scrollbars will appear automatically as the preferred size of the pnlReservation dynamically changes when you add components to it.

Related

JPanel in JScrollPane doesn't adjust size dynamically

I have a JScrollPane and a JPanel.
JScrollPane scrollPane_yst = new JScrollPane();
scrollPane_yst.setBorder(null);
scrollPane_yst.setViewportBorder(null);
panel.add(scrollPane_yst);
JPanel panel_yst = new JPanel();
panel_yst.setPreferredSize(new Dimension(150, 1000));
panel_yst.setBorder(null);
panel_yst.setBackground(Color.DARK_GRAY);
scrollPane_yst.setViewportView(panel_yst);
panel_yst.setLayout(new BoxLayout(panel_yst, BoxLayout.Y_AXIS));
During runtime, I add other components to panel_yst, but it doesn't get bigger when the components exceed its size.
(Same problem with and without setting preferred size)
ANSWER:
I found the solution. The problem was, that I set the preferred size of the panels that I lateron added onto the panel inside the scrollpane.
Because of that, the size of those panels was messed up. Just dont set the PreferredSize of the components that you add onto the panel.
I found the solution. The problem was, that I set the preferred size of the panels that I lateron added onto the panel inside the scrollpane.
Because of that, the size of those panels was messed up. Just dont set the PreferredSize of the components that you add onto the panel.

Adding panel with without layout to the NORTH of BorderLayout

Colleagues.
I'm trying to construct simple GUI in Java, where JFrame has Border Layout. I want to put JScrollPane with JTable to CENTER, and JPanel without layout to NORTH.
The problem is that JPanel doesn't visible. There is simple examle of the problem:
JFrame frame = new JFrame("Test frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Test button");
button.setBounds(10, 10, 40, 20);
JPanel panelN = new JPanel(null); // layout = null, panelN without layout
panelN.add(button);
frame.add(panelN, BorderLayout.NORTH);
JTable table = new JTable(new DefaultTableModel(4, 4));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
You have to use a LayoutManager. It's totally discouraged not using layoutManager, but if you want this you have to set panel.setBounds(..) to the panel too.
By default JPanel has FlowLayout so if you put
JPanel panelN = new JPanel(); // FlowLayout used
panelN.add(button);
frame.add(panelN, BorderLayout.NORTH);
So your frame will look like this.
Layout Managers determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container.
It's strongly recommended cause for example if you have to resizes components or show in differentes resolutions you delegate this work to layout managers
I don't know the expected behavior of a null layout, but without further requirements you might as well just instantiate with the zero-arg constructor:
new JPanel();
If you didn't set any layout to the panel, when adding components the panel don't know where to put the component, so baisicly the component don't show until you set a specific location for components one by one by component.setBounds(x,y,width,hieght) method.
Note that it's not a good practice to remove the layout manager because of the different platformes, suppose that your program working on Window and MacOS and Linux, you'v better to use the layout managers instead.
Take a look at this post also and see #Andrew Thompson's comment on my answer:
Java GUIs might have to work on a number of platforms, on different
screen resolutions & using different PLAFs. As such they are not
conducive to exact placement of components. For a robust GUI, instead
use layout managers, or combinations of them, along with layout
padding & borders for white space, to organize the components.
After all:
If you have a requirement or an assignment telling you you must use absolute layout, then use it, otherwise avoid it.
It is OK to use containers with no layout manager because you actually CAN set container's layout to NULL. And it's a nice idea to position your components with setBounds(). But in this case, you just have to consider your container. What size it need to be? A layout manager would calculate this for you, and if you don't have one, you have to set the size of your panel by yourself, according to components you have added to it.
As pointed by others here, the case it that the border-layout manager of your frame needs the preferred size of your NORTH panel (actually, the preferred height). And you have to set it, or values will be zeros and the container will become invisible. Note that for the CENTER panel this is not needed as it gets all space possible.
I had a problem like yours before and have written a fast function to resize a container according to bounds of a given component. It will be as large as needed to show this component, so dimension (w,h) and position (x,y) are considered. There's an "auto-resize" version that can be used once, after all components are added.
public static void updatePreferredSize(Container cont, Component comp) {
int w = cont.getPreferredSize().width;
int h = cont.getPreferredSize().height;
int W = comp.getBounds().x + comp.getBounds().width;
int H = comp.getBounds().y + comp.getBounds().height;
if (W>w||H>h) cont.setPreferredSize(new Dimension(W>w?W:w, H>h?H:h));
}
public static void autoPreferredSize(Container cont) {
for (Component comp : cont.getComponents())
updatePreferredSize(cont, comp);
}
You can use updatePreferredSize() after adding every component to a panel, or use autoPreferredSize() once, after all addings.
// [...]
panelN.add(button);
updatePreferredSize(panelN, button);
// [...]
// or...
// [...]
autoPreferredSize(panelN);
// [...]
frame.setVisible(true);
This way, if you do not set you north panel height with a fixed value, with help of these functions you can expect your button will be visible according the position you set it with setBounds().

How to set only the preferred width of Panel with flow layout?

I have a panel with flow layout, and it can contain a variable number of items - from 1 to 2000. I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width. The problem is, when I set preferred size of panel to something like (800,600), some items are missing, and there is no scroll. If I set up preferred size of scroll pane, then all elements in flow pane are put on one very long line.
Setting maximum size on any element seems to do nothing at all - layout managers ignore it.
How can I fix this?
I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width
You can use the Wrap Layout for this.
Don't set the preferred size of the panel. But you can set the preferred size of the scroll pane so the frame.pack() method will work.
You could use BoxLayout to do this:
JPanel verticalPane = new JPanel();
verticalPane.setLayout(new BoxLayout(verticalPane, BoxLayout.Y_AXIS));
JScrollPane pane = new JScrollPane(verticalPane);
//add what you want to verticalPane
verticalPane.add(new JButton("foo"));
verticalPane.add(new JButton("bar"));
This of course will use the preferred size of each component added. If you want to modify the preferred size for example of a JPanel, extend it and override getPreferredSize:
class MyPanel extends JPanel(){
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
}
A note: BoxLayout will take in consideration getPreferredSize, other LayoutManager may not.
Please criticize my answer, I'm not sure it's completely correct and I'm curious to hear objections in order to know if I understood the problem.

Scrollable flow panel

I need to create a panel where I can put some rectangles and it automatically reorder just inserting a scrollbar and growing up vertically. Also this panel can be resizable and again the rectangles must to be reordered to correctly be displayed inside the panel.
If I understand the question you want components to wrap to the next line so that the panel grows vertically while the width remains fixed.
If so then check out the WrapLayout
Note: the FlowLayout already supports the wrapping of components to a new row on the panel. This issue is that the preferred size calculation assumes all components are placed on a single row. The WrapLayout overrides the preferred size calculation to support the wrapping of components on a new row.
Use a JScrollPane. If you never want a horizontal scroll bar you can add the following:
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
(By default the scroll pane will add horizontal and vertical scroll bars when required.)
The scroll pane itself will only be resizeable if you add it to a Container with the appropriate layout manager; e.g.
JFrame frm = new JFrame();
frm.setLayout(new BorderLayout());
JScrollPane sp = new JScrollPane();
frm.add(sp, BorderLayout.CENTER); // Adding a component to the CENTER will cause the component to grow as the frame is resized.

Can you set a permanent size for a JPanel inside of a JFrame?

My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look
Image
Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?
I also would like to set the size of those buttons so they are not so huge (BorderLayout is being used for the buttons and TextField)
GridBagLayout is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on the API page for it. Using GridBagLayout, the components won't fill the whole grid space if you don't want them to and can even stay the size that you ask it to be. To keep a component's size from changing, I would set all three available size constraints:
water.setPreferredSize(new Dimension(20, 20));
water.setMinimumSize(new Dimension(20, 20));
water.setMaximumSize(new Dimension(20, 20));
For your buttons, I would definitely use an inner panel as Bryan mentions. You could use either a GridLayout like he suggests or a FlowLayout if you don't want all the buttons to be the same size. Add all your buttons to that inner panel instead of the main one.
If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own JPanel. Set each of those parent JPanel's to have a layout type of GridBagLayout. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout should by default lay each board out in the center of the parent JPanel. So as the window is resized, the JPanel parent area will get larger or smaller, but the checkerboard components inside will remain the same size.
Alternatively, you could have your blue squares scale to the right size as the window is resized by having each checkboard square be a JPanel with a BorderLayout layout manager and adding the JLabel (with a blue background color) to its BorderLayout.CENTER location.
As for your buttons, try something like this:
JPanel theButtonPanel = new JPanel(new BorderLayout());
JButton button1 = new JButton("Fire");
JButton button2 = new JButton("Pass");
JButton button3 = new JButton("Forfiet");
JPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8));
innerButtonContainer.add(button1);
innerButtonContainer.add(button2);
innerButtonContainer.add(button3);
theButtonPanel.add(innterButtonContainer);
Lastly, consider using a design tool for your Swing user interface. Netbeans has an excellent UI designer built into it. Download Netbeans here.
If you can setResizeable( false ) on the top level frame you can then set your layout manager to null and hard code each location and size via setBounds. This is how I would do it (contingent on resizing of course).
I have had success solving problems like these using TableLayout which is a third party layout manager. You will need to download it and read the tutorial but the key would be to set the justification to CENTER when adding the JButtons to their positions in the layout.

Categories