How do I add the JDesktopPane to JFrame using GridBagLayout and set its height and width. If I add JDesktopPane that contains JInternalFrame I don't get anything. But works well in case of GridLayout but the problem is I can't set my desired size in it as GridLayout splits equal space among each component added.
You will probably need to set the fill and weight attributes of the GridBagConstraints...
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
This will cause the component to want to push to the limits of the container and will cause the component to fill it's cell within the grid
This override the components preferred size (for the most part)
Take a look at How to Use GridBagLayout for more details...
Related
I need to design a swing GUI which has a JFrame with a Menu on top and another main panel having three more panels in center and a separate panel in the bottom of the panel. The required design of the UI is as below
But when I run my swing application I get the output like this (all the panels are packed in the center of the window)
Below is my code
import java.awt.*;
import javax.swing.*;
public class FrontEndView {
private JFrame mainFrame;
private JPanel mainPanel,subPanelUp,subPanelDown,panelLeft,panelRight,panelCenter,panelDown;
private JScrollPane scrollPane;
private JList logViewList;
private JPanel panel1;
public FrontEndView(){
this.prepareGUI();
}
public void prepareGUI(){
mainFrame=new JFrame("GUI");
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
mainFrame.setSize(xSize,ySize);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(true);
mainFrame.setLayout(new BorderLayout());
mainPanel=new JPanel();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
GridBagConstraints gridbagConstMain = new GridBagConstraints();
GridBagConstraints gridbagConstSub = new GridBagConstraints();
subPanelUp=new JPanel();
subPanelUp.setLayout(new GridBagLayout());
subPanelUp.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panelLeft=new JPanel();
panelLeft.setBorder(BorderFactory.createTitledBorder("Message Defs"));
gridbagConstSub.fill = GridBagConstraints.HORIZONTAL;
gridbagConstSub.weightx = 0.5;
gridbagConstSub.gridx = 0;
gridbagConstSub.gridy = 0;
subPanelUp.add(panelLeft, gridbagConstSub);
panelCenter=new JPanel();
panelCenter.setBorder(BorderFactory.createTitledBorder("Main Workspace"));
gridbagConstSub.fill = GridBagConstraints.HORIZONTAL;
gridbagConstSub.weightx = 0.5;
gridbagConstSub.gridx = 1;
gridbagConstSub.gridy = 0;
subPanelUp.add(panelCenter, gridbagConstSub);
panelRight=new JPanel();
panelRight.setBorder(BorderFactory.createTitledBorder("Script Viewer"));
gridbagConstSub.fill = GridBagConstraints.HORIZONTAL;
gridbagConstSub.weightx = 0.5;
gridbagConstSub.gridx = 2;
gridbagConstSub.gridy = 0;
subPanelUp.add(panelRight, gridbagConstSub);
mainPanel.add(subPanelUp,gridbagConstMain);
subPanelDown=new JPanel();
subPanelDown.setLayout(new BorderLayout());
panelDown=new JPanel();
panelDown.setBorder(BorderFactory.createTitledBorder("Log View"));
logViewList= new JList();
panelDown.add(logViewList);
gridbagConstSub.fill = GridBagConstraints.HORIZONTAL;
//gridbagConst.ipady=20;
//gridbagConst.weightx = 0.0;
gridbagConstSub.gridwidth = 5;
gridbagConstSub.gridx = 0;
gridbagConstSub.gridy = 0;
subPanelDown.add(panelDown,BorderLayout.PAGE_END);
mainPanel.add(subPanelDown, gridbagConstSub);
scrollPane=new JScrollPane(mainPanel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainFrame.add(scrollPane);
mainFrame.setVisible(true);
}
public static void main(String[] args){
FrontEndView frontEnd = new FrontEndView();
}
}
I want to fill the GridBagLayout's cells with the relevant panel/control it holds as shown in the design and also each panel should have its controls filled inside (I need to add a JList inside the panelDown whose size should be the size of the panelDown JPanel).Simply I don't need any extra space visible in my JFrame. Please guide me on what is missing in my code.
I would suggest you can use nested panels with different layout managers to solve the problem.
The default layout of a frame is a BorderLayout.
So you could create a panel and add it to the PAGE_END so it displays the entire width at the bottom.
Then you can create another panel that uses a GridLayout. You can then add 3 child panels to this panel and each panel can use its own layout. Then you add this panel to the CENTER of the frame. As the frame size changes the extra spaces will be allocated to the CENTER so the panels will dynamically grow.
Edit:
Too many panels for me to take the time to understand what is happening
I was suggesting a structure like this:
frame (which by default uses a BorderLayout)
--- CENTER
panel using GrigBagLayout
childPanel1
childPanel2
childPanel3
---- PAGE_END
JScrollPane containing the JList
When you create the JList the basic code would be:
JList list = new JList(...);
list.setVisibleRowCount(5);
JScrollPane scrollPane = new JScrollPane( list );
There is no need to create a panel just to add the list to another panel. The point of setting the visible row count is to give the JList a fixed height. Scrollbars will then appear in the scroll pane as needed.
Now that the PAGE_END has a fixed height component all the reset of the space will go to the component that you add to the CENTER of the frame.
all the panels are packed in the center of the window)
The panels are displayed at their preferred sizes when you use the GridBagLayout. If the total size of all the panels is less than the size of the scrollpane then they will be in the center. If you want the panels to fill the space available, then I believe you need to use the weightx/y constraints. Read the section from the Swing tutorial on How to Use GridBagLayout which describes all the constraints.
That is why I suggested a GridLayout instead. It will make all the panels the same size and will fill the viewport of the scroll pane without playing with constraints.
mainFrame.add(menubar,BorderLayout.NORTH);
That is not how you add a menubar to the frame.
You should be using:
mainFrame.setJMenuBar(menuBar);
You were told this in your last question. Why did you not listen to the advice??? Why should we take the time to help when you don't pay attention to what is suggested.
Based on your instructions I changed my design in a way all of the outer panels are used with Border Layout and the inner most ones with more controls were used with Grid, GridBag and FlowLayouts based on the requirement. In that way the entire design could be done nicely.
Also if a particular panel within a cell of a layout needs to be expanded, I used the setPreferredSize(new Dimension(int,int)) whenever required.
I'm trying to display two buttons next to a text field:
I gave up on the text already, but I really need the two buttons to remain small while the text field should expand with the window:
Currently, I use this layouts:
The text field and the two buttons are both in JPanel.
//JPanel group - the container
//List<JComponent> - the conponents added to JPanel
//int[] weights - weights of components
GridBagLayout lay = new GridBagLayout();
for(int i=0,l=fields.size(); i<l; i++) {
InputDef field = fields.get(i);
GridBagConstraints c = new GridBagConstraints();
if(weights.length<i) {
c.weightx = weights[i];
}
c.fill = GridBagConstraints.HORIZONTAL;
lay.setConstraints(field.getField(), c);
}
group.setLayout(lay);
In the documentation I see that for the components to fill their area horizontally, you should set the GridBagConstraints.HORIZONTAL to the constraints of the components.
Further, I read that you should set different GridBagConstraints#weightx to make the elements take different amount of space.
However running the code above doesn't do anything - the JPanel looks exactly the same with no layout manager whatsoever.
my problem is that although the scroll bar is appearing on the specific panel I want it to it's not extending as labels are added. I would like it to extend when the labels start going off the panel that they are being added to.
I have a main JPanel 'panel' which uses GridBagLayout, within that I have 5 other panels, the ones that needs a scroll bar is boardPanel which has null value for setLayout()
panel = new JPanel();
panel.setLayout(new GridBagLayout());
...
1Panel = new JPanel();
1Panel.setPreferredSize(new Dimension(480, 800));
1Panel.setLayout(null);
scrollPanel = new JScrollPanel(1Panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
...
c.weighty = 1.0;
c.weightx = 0.6;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
panel.add(scrollPanel, c);
...
I hope this is enough information, thank you so much for your help in advance.
Don't use a null layout!!!
Don't use setPreferredSize()!!!
Scrollbars will appear when the preferred size of the component is greater than the size of the scroll pane. By hardcoding a size you break this functionality.
Use a layout manager and the preferred size will change dynamically as you add components to the panel.
Read the Swing tutorial on Layout Managers
I'm learning swing gui and I get this result when I use the following code:-
The code I use :-
private void initUI() {
JTextArea visualize=new JTextArea();
visualize.setEditable(false);
//DEFINE BUTTONS....
JButton[] buttons1={addition,subtraction,division,multiplication};
JButton [] buttons2={expr,date,conversion};
JPanel numerical=new JPanel(new FlowLayout());
numerical.setPreferredSize(new Dimension(350, 50));
for(int i=0;i<buttons1.length;i++){
numerical.add(buttons1[i]);
}
numerical.setBorder(new TitledBorder("Numerical Operations"));
JPanel nonnum=new JPanel(new FlowLayout());
nonnum.setPreferredSize(new Dimension(500, 50));
for(int i=0;i<buttons2.length;i++){
nonnum.add(buttons2[i]);
}
nonnum.setBorder(new TitledBorder("Non-numerical Operations"));
JPanel operations = new JPanel(new BorderLayout(2,2));
operations.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
operations.setSize(800, 100);
operations.add(numerical,BorderLayout.WEST);
operations.add(nonnum,BorderLayout.EAST);
JTable sheet = new JTable(10,5);
add(visualize, BorderLayout.NORTH);
add(sheet,BorderLayout.SOUTH);
add(operations,BorderLayout.CENTER);
pack();
setSize(1000, 700);
setTitle("Spreadsheet Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
But what I really want is this:-
My questions :-
Why is the operations panel too long?
How can I change it's height?
Doesn't "operations.setSize(..)" work?
Try using GroupLayout.
I'm also new to swing gui and had similar problems - GroupLayout saved the day
JPanel complete=new JPanel();
GroupLayout gl=new GroupLayout(complete);
complete.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup() //this is parallel bcz you need components vertically
.addComponent(visualize) //you MUST add components to both horizontal and vertical groups
.addComponent(operations)
.addComponent(sheet)
);
gl.setVerticalGroup(gl.createSequentialGroup() //NOTE that this is sequential
.addComponent(visualize)
.addComponent(operations)
.addGap(50) //you can add gaps if you want
.addComponent(sheet)
);
add(complete);
Because that's how BorderLayout works, take a closer look at How to Use BorderLayout. The CENTRE position will occupy all the remaining space of the frame, where as the NORTH and SOUTH positions will try and honour the preferred sizes of the components.
You could use a GridBagLayout, which will allow you more control over the layout or use a series of compound layouts.
Something like...
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
add(visualize, gbc);
add(operations, gbc);
gbc.gridy = 1;
add(sheet, gbc);
It is generally discouraged to extend from a top level container like JFrame, instead you should use something like JPanel to define your UIs and then add them to the containers you want. This increases there re-usability and makes it easier to use on different containers
You may also like to take a look at How to Use Scroll Panes
SOME of us find GridBagLayout to be a royal pain, and you may not have to use it to do what you want to do.
The idea behind a layout manager is to let the layout manager control the size and position of its components so that you don't have to futz with them. MP is right, GridBag allows you a lot of control, but that also means you have to get a lot of things right to have it do what you want it to do.
So, an alternative: Make a JPanel to hold the visualize and operations panels; give this new panel a BoxLayout with a Y_AXIS orientation, then add them in the order you want them to appear, top-to-bottom.
Then put sheet in the BorderLayout.CENTER of the JFrame. In fact, I think you'll want to take MP's advice and go through a tutorial on JScrollPane; as best I remember, you create the panel, then create the JScrollPane instance with the panel as a construction parameter, then add the scrollpane instance to the JFrame (in the CENTER, in your case).
Being in the center, it will then expand and contract as the user changes window size.
Good luck. Swing takes some getting used to.
In my Java application, I'm writing a component that is used to view PDF files. I had a pretty slick implementation where the user could click on the PDF and drag it to view the areas that didn't fit on the screen. But my boss didn't like it, so now I have to use scroll bars. So I did the obvious thing and just put it into a JScrollPane, but almost no matter what I do it refuses to work.
The PDF just gets converted to a BufferedImage and then I convert it to an ImageIcon so I can add it to a JLabel which gets added to a JScrollPane.
I have a PDFViewer class which subclasses JScrollPane, and the important code is here:
private void drawPDF() {
PDFRenderer renderer = new PDFDrawer(pdfFile);
BufferedImage image = renderer.makeImage(page);
JLabel img = new JLabel(new ImageIcon(image));
this.setViewportView(img);
}
Now I have a separate class which subclasses JFrame that I need to add my PDFViewer to.
It works as long as I don't use a layout and add the PDFViewer directly to the JFrame. If I even just add the JScrollPane to a JPanel and then add the JPanel to the JFrame the scroll bars disappear and it looks like I just added the JLabel directly. The image is too big for this, and it gets cut off easily.
I need to add some controls to the frame as well, so I set up a really basic GridBagLayout with the PDFViewer as the only component being added. And with the following code I get a window that looks like this.
GridBagLayout glayout = new GridBagLayout();
GridBagConstraints c;
setLayout(glayout);
PDFViewer viewer = new PDFViewer("foo.pdf");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 1;
add(viewer, c);
setVisible(true);
Why does the JScrollPane get smooshed like that when I just simply add it to a layout instead of directly to the JFrame? I found out that it works with GridLayout, but a GridLayout is not what I want.
You need at least ONE component with the weightx/y set to a non zero value for GridBagLayout to work.
You need to specify
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
This means that it will take all available space that is not used by other components. I suggest reading up on GridBagLayout for more information.
Try adding:
c.fill = GridBagConstraints.BOTH;
This should ensure that your panel is resized in both directions when you resize. Incidentally if this is the only component then consider using BorderLayout and adding the component to BorderLayout.CENTER.
c.weightx = 1.0;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;
before adding the viewer.
You need to set the preferredSize(), minimumSize() and maximumSize() of the component you are adding to the JScrollpane. Or you can set the cell to expand horizontally and vertically as far as possible by adding
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
to the GridBagConstraints.
Try setting prefferedsize(setPrefferedSize()) to the component which you are adding to ScrollPane.