How to add many components to a JFrame in a format - java

I have a JPanel, 4 ComboBoxes, and a button. I want to have a 700 x 500 JFrame, with the panel taking up the left 500 x 500. The right side I want, vertically, 2 combo boxes, another 2 combo boxes, and then the button. Hopefully this makes sense: I just want to have them all visible and I want the boxes paired in groups of 2. Example code of what I've tried is here:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JButton;
public class Test extends JFrame{
public Test () {
super();
//setLayout(new FlowLayout());
JPanel canvas = new JPanel();
canvas.setBackground(Color.red);
canvas.setSize(500, 500);
JComboBox field1 = new JComboBox();
JComboBox field2 = new JComboBox();
JComboBox field3 = new JComboBox();
JComboBox field4 = new JComboBox();
JButton button = new JButton();
JPanel info = new JPanel();
info.setBackground(Color.blue);
info.add(field1, BorderLayout.NORTH);
info.add(field2, BorderLayout.EAST);
info.add(field3, BorderLayout.CENTER);
info.add(field4, BorderLayout.WEST);
info.add(button, BorderLayout.SOUTH);
add(info, BorderLayout.EAST);
add(canvas, BorderLayout.WEST);
setTitle("TEST");
setSize(700, 500);
}
public static void main (String[] args) {
JFrame testFrame = new Test();
testFrame.setVisible(true);
}
}
Any help or suggestions about how to go about laying this out would be great.

If you want your combo buttons and the button vertically stacked on top of each other, I would use a grid layout instead of a border layout. Just make the border layout have 1 column and 5 rows.

Related

How do I put two Jpanels/Jbuttons in the borderlayout north section?

How do I display two JPanels in the 'North' in borderlayout?
Here's and example code that outputs a GUI with three distinct rows, Top, Middle, Bottom. There's one button covering the first row, 3 buttons covering the second row, and one covering the bottom row.
package borderLayoutDemo;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
public class BorderLayoutDemo {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame fj = new JFrame("Demonstration of Border Layout");
fj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtn1 = new JButton("UP");
JButton jbtn2 = new JButton("DOWN");
JButton jbtn3 = new JButton("LEFT");
JButton jbtn4 = new JButton("RIGHT");
JButton jbtn5 = new JButton("MIDDLE");
JPanel pnl = new JPanel();
pnl.setLayout(new BorderLayout());
pnl.add(jbtn1, BorderLayout.NORTH);
pnl.add(jbtn2, BorderLayout.SOUTH);
pnl.add(jbtn3, BorderLayout.WEST);
pnl.add(jbtn4, BorderLayout.EAST);
pnl.add(jbtn5, BorderLayout.CENTER);
fj.add(pnl);
fj.pack();
fj.setVisible(true);
}
}
Output of above code:
output of above code
However, I'd like there to be two jpanels in the North section so it'd make 4 "rows" like this:
|---------------button--------------| //north
|---------------button2-------------| //north
----------------center--------------- //center
|---------------button3-------------| //south
I've tried simply just adding it as follows:
pnl.add(jbtn1, BorderLayout.NORTH);
pnl.add(jbtn2, BorderLayout.NORTH);
But what happens here is the second button just replaces the first one:
|---------------button2-------------| //north
----------------center--------------- //center
|---------------button3-------------| //south
How would I get two rows in the north layout area?
Creating a more complex GUI is straightforward when you think of a GUI as a JFrame with as many JPanels as necessary to define the GUI.
Here's the GUI you were looking for.
I created a JPanel for each section of the JFrame (NORTH, CENTER, and SOUTH). Each of those JPanels used a BorderLayout so that when you expand the GUI, the NORTH and SOUTH buttons stay the same height.
Here's the complete runnable example code.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BorderLayoutDemo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorderLayoutDemo());
}
#Override
public void run() {
JFrame fj = new JFrame("Demonstration of Border Layout");
fj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fj.add(createNorthPanel(), BorderLayout.NORTH);
fj.add(createCenterPanel(), BorderLayout.CENTER);
fj.add(createSouthPanel(), BorderLayout.SOUTH);
fj.pack();
fj.setLocationByPlatform(true);
fj.setVisible(true);
}
private JPanel createNorthPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button1 = new JButton("North Button");
panel.add(button1, BorderLayout.NORTH);
JButton button2 = new JButton("North Button 2");
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("Center Button");
panel.add(button, BorderLayout.CENTER);
return panel;
}
private JPanel createSouthPanel() {
JPanel panel = new JPanel(new BorderLayout());
JButton button = new JButton("South Button");
panel.add(button, BorderLayout.SOUTH);
return panel;
}
}

Java resizing individual components of JPanel

I have a JPanel with Box.createVerticalBox() layout containing five JPanels. (1) Labels, (2) a table (3) a JTextField (4) a JTextArea (5) buttons.On resize:
labels should stick to top left corner and keep the same size,
JTextField should stick to left size between (2) and (4) and expand to full width of the frame
Buttons should stick to bottom right corner and keep the same size,
JTable and JTextArea should expand to full width of the frame and equally divide remaining space
I've tried several layouts, but couldn't make resizing work.
To run this program two classes are required EditPanel.java :
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class EditPanel extends JPanel {
private JPanel p1Labels;
private JPanel p2Table;
private JPanel p3ecnTitle;
private JPanel p5Buttons;
private JTextField fieldK;
private JTextField fieldS;
private JScrollPane myScrollBar;
private Box theBox;
public EditPanel() {
init();
}
public void init() { // Creating a vertical Box layout with five sections, placing jpanels there
//First panel with buttons
p1Labels = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
fieldK = new JTextField("Animal");
fieldS = new JTextField("Fox");
p1Labels.add(new JLabel("Kindom: "));
p1Labels.add(fieldK);
p1Labels.add(new JLabel("Species: "));
p1Labels.add(fieldS);
//Second panel with a table
p2Table = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
String[] columnNames = {"First", "Second", "Third", "Fourth"};
Object[][] data = {{"11", "12", "13", "Forteen"},{"21", "22", "23", "Twenty four"}};
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane1 = new JScrollPane(new JTable(data, columnNames));
table.setFillsViewportHeight(true);
p2Table.add(scrollPane1, BorderLayout.CENTER);
//Third panel with a JTextField
p3ecnTitle = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
p3ecnTitle.add(new JLabel("Title: "));
p3ecnTitle.add(new JTextField("", 14));
//Forth panel with JTextArea
//p4TextArea = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));//tried this too
JTextArea ecnArea = new JTextArea(10, 20);
ecnArea.setText("");
ecnArea.setName("Note");
ecnArea.setLineWrap(true);
ecnArea.setWrapStyleWord(true);
myScrollBar = new JScrollPane(ecnArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//Fifth container with buttons
p5Buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 2));
p5Buttons.add(new JButton("SAVE"));
p5Buttons.add(new JButton("DELETE"));
p5Buttons.add(new JButton("CANCEL"));
//Placing everything in a container
theBox = Box.createVerticalBox();
theBox.add(p1Labels);
theBox.add(p2Table);
theBox.add(p3ecnTitle);
//theBox.add(p4TextArea);
theBox.add(myScrollBar);
theBox.add(Box.createVerticalGlue());
theBox.add(p5Buttons);
this.add(theBox);
}
}
And the main.java
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame myFrame;
myPanel EditECNDialog;
myFrame = new JFrame();
EditECNDialog = new myPanel();
myFrame.setTitle("Notes");
myFrame.add(EditECNDialog);
myFrame.pack();
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}
}
Which Layout handles resizing the best? Can boxlayout handle resizing?
GridBagLayout is the best layout manager for your app. See https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
You can use a GridBagLayout as Wabbi has already suggested. However is does have the limitation I noted in the comments.
However, if you truly want the textarea and table to always be the same size then you can use the Relative Layout. This layout will first allocate space to components with a fixed size. Then any space remaining is allocated to the components with a relative constraint.
So the basic code would be:
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill( true );
JPanel panel = new JPanel( rl );
panel.add(labelPanel);
panel.add(tableScrollPane, new Float(1));
panel.add(textField);
panel.add(textAreaScrollPane, new Float(1));
panel.add(buttonsPanel);
Now the table and text area will grow/shrink equally as the frame is resized.
Can boxlayout handle resizing?
Yes it can handle this type of resizing. Box layout respects the maximum size of a component. So if you override the getMaximumSize() method of your panels to return getPreferredSize(), then the panels will not grow in height.
So extra space will be given to the scrollpanes of the text area and table. Again, same concern. Each component will originally be allocated space based on its preferred size.
You should use one variable for gridbagconstraints. This way you can do c.gridy++; c.gridx=0; and c.gridx++;
It will be easier to insert new components later.
Explicit d.gridy=4; makes inserting new components difficult.

Trying to add a scrollbar to a JPanel with GridLayout, but the JCheckBoxes just get made smaller instead

So I'm trying to set up a Gui in Java which holds a list of checkboxes. What determines the length of the list is the highlighted checkboxes. However, when I add more things to the list the checkboxes just get smaller to fit the panel. I've added a vertical scrollbar, but this just doesn't do anything. Is there something I have to do to stop the GridLayout from resizing what it holds or is it the wrong layout?
package darrt;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestForScrollBat {
public static void main(String[] args){
new TestForScrollBat();
}
public TestForScrollBat(){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(50, 30, 300, 50);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JLabel label = new JLabel(" Soc Categories");
JCheckBox soc1 = new JCheckBox("Blood and Lymphatic System Disorder");
JCheckBox soc2 = new JCheckBox("Cardiac Disorders");
JCheckBox soc3 = new JCheckBox("Congenital, familial and Genetic Disorders");
JButton jbtn = new JButton("Go!");
panel.add(label);
panel.add(soc1);
panel.add(soc2);
panel.add(soc3);
panel.add(jbtn);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
I had it before so that it would add a scroll to this panel, but now it doesn't even do that.. It just creates a new JPanel on the JFrame
Your problem is about the following lines in your code:
scrollPane.setBounds(50, 30, 300, 50);
You should not set static sizes and locations when using layouts. You are telling a specific size and location to the scrollPane while you had add it to the center of the contentPane before. These two are in conflict.
And next problem is about this line:
frame.add(panel);
This line will detach the panel from you JScrollPane and add it directly to the contentPane of the JFrame.
By deleting/commenting these lines, your problem will be solved.

Dynamically add fixed-height panels to a JScrollPane

JPanel panel = new JPanel(new GridLayout(0,1));
JScrollPane contentpane = new JScrollPane(panel);
JButton add = new JButton("ADD");
add.actionListener(new ActionListener() {
public void actionPerformed(){
MyPanel newpanel = new MyPanel("title","Button"); //MyPanel is a class which extends JPanel and contains constructor MyPanel(String TitleToSet ,String ButtonTitleTOAdd)
panel.add(newpanel);
panel.repaint();
}) ;
I have used this code thinking that it will add the MyPanel to the grid layout dynamically and "panel" would be scrollable if more "MyPanel"s are added. However, this was not the case, 1st "MyPanel" filled whole "panel" and on adding second "MyPanel" (by clicking button "Add"), the 1st "MyPanel" was shrinked to make space for second one to be added.. and on adding more, all the "MyPanel"s were fit in the viewport instead of making the "panel" scrollable.. How to add those "MyPanel"s dynamically and making the "panel" scrollable on adding more of those?? Any help would be appreciated.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html :
By default JScrollPane uses ScrollPaneLayout to handle the layout of
its child Components. ScrollPaneLayout determines the size to make the
viewport view in one of two ways:
[...]
getPreferredSize is used.
You should add the line
panel.setPreferredSize(new Dimension(0, panel.getComponents().size() * SUB_PANEL_HEIGHT));
to your ActionListener.
Full example:
package main;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(400, 400));
frame.setSize(400, 400);
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("BOO"));
panel.add(new JButton("BBBB"));
JScrollPane contentpane = new JScrollPane(panel);
frame.add(contentpane);
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel newpanel = new JPanel();
newpanel.add(new JLabel("LOL"));
panel.add(newpanel);
System.out.println(100 * panel.getComponents().length);
panel.setPreferredSize(new Dimension(0, 100 * panel.getComponents().length));
contentpane.validate();
}
}).start();
frame.setVisible(true);
}
}

How do I center an object in java

I want to make a simple program that will have one button and multiple fields. When I was planning this out in my head I wanted to use a gridlayout, or at least cent the button at first since I am learning. Here is what I have so far, my question that I am leading to is where do I put in my grid layout, or do I set the alignment center in the panel, frame or button?
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
//button
button.setSize(50, 50);
//Field
field.setSize(250, 25);
//Frame
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(panel);
frame.add(field);
frame.add(button);
}
}
Always add the components in a Container of the JFrame. Set the Layout of Container as GridLayout. For example You can change your code as follows:
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
Container c = frame.getContentPane();
c.setLayout(new GridLayout(3,1));//Devides the container in 3 rows and 1 column
c.add(panel);//Add in first row
c.add(button);//Add in second row
c.add(field);//Add in third row
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In an approach where you extend your class from JFrame, you could simply set where you would like to add the components. If you have a panel with ex. a button, you could add it like this:
add(panel, BorderLayout.CENTER);
Hope this helps.

Categories

Resources