Java Layout for scrollable panels - java

I am trying to create a JPanel that is resizable & scrollable and contains x smaller inner panels. Each inner panel can be as wide as it wants/needs. BUT the depth should be a preferred size.
Like:
So far my code is:
public class TestSize {
public static void main(String[] args) {
JFrame F = new JFrame();
F.setVisible(true);
JPanel P = new JPanel();
P.setLayout(new BorderLayout());
JScrollPane scrollPane = new JScrollPane(P);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(900,900));//.setBounds(50, 30, 300, 50);
JPanel S = new JPanel();
S.setBackground(Color.GREEN);
S.setPreferredSize(new Dimension(900,200));
JPanel S2 = new JPanel();
S2.setBackground(Color.GREEN);
S2.setPreferredSize(new Dimension(900,200));
P.add(S,BorderLayout.NORTH);
P.add(S2,BorderLayout.NORTH);
F.add(scrollPane);
F.pack();
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
But when I have added a single inner panel it fills all the space vertically - which is not what I want:

//P.setLayout(new BorderLayout());
Why did you set the layout to a BorderLayout? You can only add 1 component to the NORTH. Is that what you want? Read the section from the Swing tutorial on Using Layout Managers and pick a more appropriate layout manager. Bookmark the tutorial link as it provides the basics for Swing programming.
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
Why did you set these properties? These are the default values.
scrollPane.setPreferredSize(new Dimension(900,900));
Why would you set the height to be 900. You only want the scrollpane to contain components of height 200? In general you should NOT be setting the preferred size. Let the frame.pack() method do its job.
S.setBackground(Color.GREEN);
Why would you set the background color of both panels to be the same. How can you tell if the two panels get added? Make them different color for an easy visual.

In BoxLayout, there are different methods of using invisible components as filler. I don't think you will want to use a "rigid area", since I think you want to have a variable number of inner panels. You may want to try using vertical glue or custom Box.Filler.
Another solution might be to put a JPanel between your JFrame and your ScrollPane that uses a BorderLayout, and put the scrollpane in the BorderLayout.NORTH of that panel. Components in BorderLayout.NORTH get resized horizontally, but they do not get resized vertically. Essentially, they just get pushed to the top of the panel.
Edit:
I think you will want something like this:
JFrame F = new JFrame();
F.setVisible(true);
F.setLayout(new BorderLayout());
JPanel P = new JPanel(new BoxLayout(P, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(P);
JPanel S = new JPanel();
S.setBackground(Color.GREEN);
JPanel S2 = new JPanel();
S2.setBackground(Color.BLUE);
P.add(S);
P.add(S2);
F.add(scrollPane, BorderLayout.NORTH);
F.pack();
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You said you want it resizeable, so I don't see why you would set the preferred size of the frame. This way it will just fit to the panels inside.

Related

How do I move a JLabel that is stuck and won't move?

Here is the code, when the image is put onto the background it just stays stuck to the left wall no matter what code I add to move it. I have tried setLocation and setBounds. All I want to do is move the image to the bottom left but, not fully on the walls of the frame.
JFrame window = new JFrame();
window.setSize(800,480);
window.setTitle("Battle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
JLabel background = new JLabel();
ImageIcon icon = new ImageIcon("background2.png");
background.setIcon(icon);
background.setLayout(new BorderLayout());
window.setContentPane(background);
JLabel p1 = new JLabel();
p1 = a.getImage();
background.add(p1);
p1.setLocation(500,500);
p1.setVisible(true);
window.setVisible(true);
window.setLayout(new BorderLayout());
...
window.setContentPane(background);
The first statement doesn't do anything because the second statement replaces the content pane of the frame, to the layout manager will be whatever layout manager you set for the "background" component.
All I want to do is move the image to the bottom left,
Well you set the layout manager to a BorderLayout so you need to take advantage of the BorderLayout. Read the section from the Swing tutorial on How to Use BorderLayout for working examples.
So the first thing you need to do is specify the proper constraint to have the component displayed at the bottom:
//background.add(p1); // defaults to BorderLayout.CENTER if no constraint is specified
background.add(p1, BorderLayout.PAGE_END);
Test this and the image will be at the bottom, but it is still centered.
So now you need to set a property on the label to tell the label to paint itself left aligned:
label.setHorizontalAlignment(JLabel.LEFT);
not fully on the walls of the frame
If you need extra space around the image then you can add a Border to the label. Using the above link read the section from the tutorial on How to Use Borders. You can use an EmptyBorder to give the extra space.
One way to do this would be to add extra "left panel" container so we can position your label on the left and bottom
public static void main(String[] args) {
JFrame window = new JFrame();
window.setSize(800, 480);
window.setTitle("Battle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel();
background.setBackground(Color.gray);
background.setLayout(new BorderLayout());
background.setOpaque(true);
window.setContentPane(background);
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
background.add(leftPanel, BorderLayout.WEST); // stick our left side bard to the left side of frame
JLabel p1 = new JLabel();
p1.setText("Im here");
p1.setLocation(500, 500);
p1.setVisible(true);
p1.setBackground(Color.black);
p1.setOpaque(true);
leftPanel.add(p1, BorderLayout.SOUTH); // add our label to the bottom
window.setVisible(true);
}
Results:

JTabbedPane in JPanel?

I have a simple problem when I want to add tabs in my jpanel. The alignment of the tabs get horizontal instead of vertical, wich looks like crap =/.
It looks like this:
If I discard the panel instead and add the tabbedPane directly to the frame, everything works fine.
If you uncomment the three lines of code and remove the getContentPane().add(jtp); you can reproduce my probleme.
working Code:
public class TabbedPane extends JFrame
{
public TabbedPane()
{
setTitle("Tabbed Pane");
setSize(300, 300); // set size so the user can "see" it
JTabbedPane jtp = new JTabbedPane();
// JPanel panel = new JPanel();//uncomment all three lines
// panel.add(jtp);
// getContentPane().add(panel);
getContentPane().add(jtp);//remove me
JPanel jp1 = new JPanel();// This will create the first tab
JPanel jp2 = new JPanel();// This will create the second tab
JLabel label1 = new JLabel();
label1.setText("This is Tab 1");
jp1.add(label1);
jtp.addTab("Tab1", jp1);
jtp.addTab("Tab2", jp2);
JButton test = new JButton("Press");
jp2.add(test);
setVisible(true); // otherwise you won't "see" it
}
public static void main(String[] args)
{
TabbedPane tab = new TabbedPane();
}
}
Thanks a lot!
If I discard the panel instead and add the tabbedPane directly to the frame, everything works fine.
The default layout of JPanel is FlowLayout, which "lets each component assume its natural (preferred) size." The default layout of JFrame is BorderLayout, the CENTER of which ignores preferred size. In either case, invoking setSize() precludes the layout from functioning initially; re-size the frame to see the effect. Instead, use pack(), which "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents."
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true); // otherwise you won't "see" it
There are many things I would change in that code, starting with the recommendations of #trashgod. OTOH this is the minimal change needed in order to stretch the tabbed pane to the width/height of the parent container.
// give the panel a layout that will stretch components to available space
JPanel panel = new JPanel(new GridLayout());//uncomment all three lines
panel.add(jtp);
getContentPane().add(panel);
//getContentPane().add(jtp);//remove me
For more details see this answer.
Well firstly you can try this:
JPanel panel = new JPanel();//uncomment all three lines
panel.setLayout(new GridLayout());
JPanel jp1 = new JPanel();// This will create the first tab
JPanel jp2 = new JPanel();// This will create the second tab
JLabel label1 = new JLabel();
label1.setText("This is Tab 1");
jp1.add(label1);
jtp.addTab("Tab1", jp1);
jtp.addTab("Tab2", jp2);
JButton test = new JButton("Press");
jp2.add(test);
getContentPane().add(jtp);
and in the main:
TabbedPane tab = new TabbedPane();
tab.pack();
tab.setVisible(true);
May I suggest using MigLayout to set layouts, it will make your life easier. Hope it helps.
Try GridbagLayout. Once you have mastered it, you can design UI of any sort with this layout.
I agree with prasanth regarding the use of GridBagLayout
I have gone through this problem once and I solved it by adding the JTabbedPaneto the panel via GridBagLayout, make sure you add the JTabbedPane using the ipadx and ipady according to your requirements in your GridBagConstraints object
e.g.
JPanel myPanel=new JPanel();
myPanel.setLayout(new GridBagLayout());
JTabbedPane jTP=new JTabbedPane();
jTP.add("Tab1",new JPanel());//substitute your component instead of "new JPanel"
GridBagConstraints myConstraints=new GridBagConstraints();
myConstraints.ipadx=400;//streches the component being added along x axis - 200 px on both sides
myConstraints.ipady=600;//streches the component being added along y axis - 200 px on both sides
myPanel.add(jTP,myConstraints);
You can adjust both these properties according to what is perfect for your need

How does one add a JScrollPane to a JPanel

I have been searching around for an easy way to implement a JScrollPlane. I am trying to add it to a JPanel, and it will contain a dynamic number of JPanels (which will be filled with other stuff).
Here is my (failing miserably) attempt to make said JScrollPane:
final JPanel info = new JPanel();
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
info.setLayout(new GridLayout(0,1));
info.setLocation(10,78);
info.setSize(420,490);
infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
The primary problem you're having is the fact that the default layout manager's layout is set to FlowLayout, which means that the JScrollPane will want to use it's preferred size to be layout with, which may not fill the entire panel.
Instead, use a BorderLayout
final JPanel info = new JPanel(new BorderLayout()); // <-- Change me :D
final JScrollPane infoS = new JScrollPane(info,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// These are bad ideas, setLocation and setSize won't work, as the panel should be
// under the control of a layout manager
//info.setLocation(10,78);
//info.setSize(420,490);
//infoS.setPreferredSize(new Dimension(600, 600));
gui.add(infoS);
In this example, a series of nested panels are added to a panel having BoxLayout. That panel is used to create a JScrollPane which is then added to a JFrame.
public class BoxTest extends JPanel {
...
JScrollPane jsp = new JScrollPane(this,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
...
JFrame f = new JFrame();
f.add(jsp); // BorderLayout.CENTER, by default

How can I place a component in a JLayeredPane right below an existing component?

I have a JTextField, and right below it I want to show a JLabel placed in a JLayeredPane (I will use it for autosuggestions later on).
How can I place my JLabel in JLayeredPane right below the JTextField?
Here is some code I have, and the current result shown in the screenshot below:
public static void main(String[] args) {
JTextField field = new JTextField();
JLabel lbl = new JLabel("Hello");
lbl.setBackground(Color.YELLOW);
lbl.setOpaque(true);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setLayout(new GridLayout(0,1));
layeredPane.add(lbl, (Integer) (JLayeredPane.POPUP_LAYER - 10));
layeredPane.setPreferredSize(field.getPreferredSize());
JPanel panel = new JPanel(new BorderLayout());
panel.add(field, BorderLayout.NORTH);
panel.add(layeredPane, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(panel);
frame.setSize(200, 360);
frame.setVisible(true);
}
Second try:
public static void main(String[] args) {
JTextField field = new JTextField();
JLabel lbl = new JLabel("Hello");
lbl.setBackground(Color.YELLOW);
lbl.setOpaque(true);
lbl.setBounds(field.getBounds().x, field.getBounds().y,
field.getBounds().width, field.getBounds().height);
JPanel popPanel = new JPanel(new BorderLayout());
popPanel.add(lbl, BorderLayout.NORTH);
popPanel.setLocation(field.getLocation().x+10, field.getLocation().y+20);
popPanel.setPreferredSize(field.getPreferredSize());
JFrame frame = new JFrame();
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.setLayout(new GridLayout(0,1));
layeredPane.add(popPanel, (Integer) (JLayeredPane.POPUP_LAYER - 10));
JPanel panel = new JPanel(new BorderLayout());
panel.add(field, BorderLayout.NORTH);
frame.add(panel);
frame.setSize(200, 360);
frame.setVisible(true);
}
Add the layeredPane to the "CENTER", not the SOUTH.
However, your understanding a layed pane seems to be a little confused. You use a layered pane when you want multiple components to be displayed on top (stacked?) of one another. You are still using the layered pane in 2 dimensions which is unnecessary. YOu can just use a panel for this.
If you want to popup a list of suggestions then you should just use a JPopupMenu and position it below the text field. Read the section from the Swing tutorial on Bringing up Popup Menus.
First of all, I don't think you should use a JLayeredPane for that, but just a permanent label.
If you do use a layered pane, you'll have to compute where the text field ends (y = field.getY() + field.getHeight()) and set your JPanel at 'panel.setLocation(0, y)' inside the JLayeredPane (provided the JLayeredPane has the same starting position as the underlying JFrame). You could equivalently position the JLayeredPane at (0, y) and put the label at (0, 0) within that layered pane.
You have to make sure this is done every time the components are resized.
why not using AutoComplete ComboBox / JTextField and if you don't want to display JComboBox, then there is AutoCompleted JTextField, and for somehow reduced autosuggestions, would be better look for undecorated JDialog/Window with JTable with one TableColum and without TableHeaded in the JScrollPane, just with plain RowSorter, very simle job

Automatically size JPanel inside JFrame

I have a JPanel subclass on which I add buttons, labels, tables, etc. To show on screen it I use JFrame:
MainPanel mainPanel = new MainPanel(); //JPanel subclass
JFrame mainFrame = new JFrame();
mainFrame.setTitle("main window title");
mainFrame.getContentPane().add(mainPanel);
mainFrame.setLocation(100, 100);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
But when I size the window, size of panel don't change. How to make size of panel to be the same as the size of window even if it was resized?
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
mainFrame.setLayout(new BorderLayout());
(Do this before adding components to the JFrame)
If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.
Ya, I know this 'solution' is not good but use it as a safety net.
;)
From my experience, I used GridLayout.
thePanel.setLayout(new GridLayout(a,b,c,d));
a = row number, b = column number, c = horizontal gap, d = vertical gap.
For example, if I want to create panel with:
unlimited row (set a = 0)
1 column (set b = 1)
vertical gap= 3 (set d = 3)
The code is below:
thePanel.setLayout(new GridLayout(0,1,0,3));
This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.
As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);
GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

Categories