How do I arrange JPanels from top to bottom? - java

I'm currently self-studying Java. I'm learning Graphical User Interface(GUI) programming.
I want JPanels to be arranged from top to bottom in a JFrame.First of all,I have a JLabel added to the first JPanel. The second JPanel has 5 JRadioButtions. The third JPanel has a JButton and a JLabel.
When the JButton is pressed,the JLabel in the 3rd JPanel shows some text.
I used BoxLayout(BoxLayout.X_AXIS) for all the JPanels and added all 3 of them into a JFrame which has FlowLayout(). Here is a small piece of code:
class GUI extends JFrame implements ActionListener {
JPanel pan1,pan2,pan3; //3 JPanels
JRadioButton rad1,rad2,rad3,rad4,rad5; //5 RadioButtons
JButton button; //A JButton
JLabel label; //A JLabel
public GUI(String header)
{
super(header);
setLayout(new FlowLayout()); //set FlowLayout to JFrame
setBounds(350,325,600,125);
setResizable(false);
creator();
adder();
commander();
add(pan1);
add(pan2);
add(pan3); //Add all 3 panels to JFrame
}
private void adder()
{
pan1.setLayout(new BoxLayout(pan1,BoxLayout.X_AXIS));
pan2.setLayout(new BoxLayout(pan2,BoxLayout.X_AXIS));
pan3.setLayout(new BoxLayout(pan3,BoxLayout.X_AXIS)); //Layout for all 3 JPanels
pan1.add(new JLabel("Choose a Security Level"));
ButtonGroup group=new ButtonGroup();
group.add(rad1);
group.add(rad2);
group.add(rad3);
group.add(rad4);
group.add(rad5);
pan2.add(rad1);
pan2.add(rad2);
pan2.add(rad3);
pan2.add(rad4);
pan2.add(rad5);
pan3.add(button);
pan3.add(label);
}
private void creator()
{
pan1=new JPanel();
pan2=new JPanel();
pan3=new JPanel();
rad1=new JRadioButton("Security Level 1");
rad2=new JRadioButton("Security Level 2");
rad3=new JRadioButton("Security Level 3");
rad4=new JRadioButton("Security Level 4");
rad5=new JRadioButton("Security Level 5");
button=new JButton("Move On");
label=new JLabel();
}
private void commander()
{
rad1.addActionListener(this);
rad2.addActionListener(this);
rad3.addActionListener(this);
rad4.addActionListener(this);
rad5.addActionListener(this);
rad1.setActionCommand("radio1");
rad2.setActionCommand("radio2");
rad3.setActionCommand("radio3");
rad4.setActionCommand("radio4");
rad5.setActionCommand("radio5");
button.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
//When button is pressed,the text in label changes
if(evt.getActionCommand().equals("radio1"))
label.setText("Very Easy to bypass");
else if(evt.getActionCommand().equals("radio2"))
label.setText("Easy to bypass");
else if(evt.getActionCommand().equals("radio3"))
label.setText("Can bypass Sometimes");
else if(evt.getActionCommand().equals("radio4"))
label.setText("Hard to bypass");
else if(evt.getActionCommand().equals("radio5"))
label.setText("Very Hard to bypass");
else
{ //Code here
}
repaint();
//More code here....
}
}
This is the output I'm getting when I select the first radiobutton(Forget the green colour):
I want the "Very easy to Bypass" text to be placed above the "Move on" button and below all the JRadioButtons. I can increase the size of the JFrame so that there will be enough space. My questions are:
Which Layout should I use to achieve this?
Should this layout be applied just for the JFrame or all 3 JPanels?

you must use GridLayout
Its very easy to use it, just add it like this. Take care of the import commands. :)
JFrame frame = new JFrame(new GridLayout(3,5));

Use GridLayout
GridLayout layout = new GridLayout(0, 1, 0, 5);
setLayout(layout);
What I would do to add 5 JPanels:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PanelAdd extends JFrame {
JPanel [] panels ;
public PanelAdd() {
GridLayout layout = new GridLayout(0, 1, 0, 5);
setLayout(layout);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setSize(400, 350);
}
public static void main(String [] args) {
PanelAdd add = new PanelAdd();
add.addPanels();
add.setVisible(true);
}
private void addPanels() {
panels = new JPanel[5];
for (int i = 0 ; i < panels.length ; i++) {
panels[i] = new JPanel();
panels[i].add(new JLabel("This Is Panel "+i));
add(panels[i]);
}
}
}
In this example, I made an array of 5 JPanels and add them through a loop.
I used GridLayout for the job.
This is just a hint for your answer

when you call add method from jframe,you can also give specified position to your panel in frame
like this:
JPanel pan1,pan2,pan3; //3 JPanels
JRadioButton rad1,rad2,rad3,rad4,rad5; //5 RadioButtons
JButton button; //A JButton
JLabel label; //A JLabel
public GUI(String header)
{
super(header);
setLayout(new FlowLayout()); //set FlowLayout to JFrame
setBounds(350,325,600,125);
setResizable(false);
creator();
adder();
commander();
add(pan1,BorderLayout.NORTH);
add(pan2,BorderLayout.CENTER);
add(pan3,,BorderLayout.SOUTH); //Add all panels to JFrame
}
good luck

Related

Resizing JPanel With BorderLayout

I am trying to resize the center panel of my BorderLayout but the size is not changing. It keeps filling the rest of the frame that is available. I have tried setting the preferred size but has no effect. I would like how size of the frame but only need a portion of the center to be actually a panel for later use.
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class Gui extends JFrame {
Border blackline = BorderFactory.createLineBorder(Color.black);
private JPanel board;
private JPanel buttons;
private JButton setMissing, by4, by8;
public Gui(){
setUpGui();
}
public void setUpGui(){
this.setSize(1000,1000);
this.setTitle("Comp361 Assignment One");
addButtons();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board = new JPanel();
board.setPreferredSize(new Dimension(400,400));
this.add(board, BorderLayout.CENTER);
//Sboard.setBackground(Color.Gray);
board.setBorder(blackline);
this.setVisible(true);
}
public void addButtons(){
buttons = new JPanel(new FlowLayout());
setMissing = new JButton("Set X");
by4 = new JButton("4 by 4");
by8 = new JButton("8 by 8");
buttons.add(setMissing);
buttons.add(by4);
buttons.add(by8);
this.add(buttons,BorderLayout.PAGE_START);
}
public static void main (String[] args){
new Gui();
}
}
For extra padding around the central panel, you might put it to a panel with GridBagLayout (with no constraint) to center it, then add the GBL panel to the CENTER of the BorderLayout.

JButton array buttons not visible unless button not from array is added

I have a array of JButtons that do not want to be visible unless I add another JButton before the loop for the array of buttons.
Window class:
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
private Container mContainer = new Container();
public Window()
{
super();
this.setTitle("Calculator");
this.setSize(200, 300);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mContainer.setBorder(null);
mContainer.setBackground(Color.GRAY);
mContainer.setOpaque(true);
this.setContentPane(mContainer);
//Panels
JPanel panel = new JPanel();
JPanel center = new JPanel();
center.setBackground(Color.GRAY);
center.setBorder(null);
JPanel displayOutput = new JPanel();
displayOutput.setBackground(Color.GRAY);
this.getContentPane().add(panel);
//TextArea
JTextArea textArea = new JTextArea(1, 20);
textArea.setForeground(Color.WHITE);
textArea.setBackground(Color.GRAY);
textArea.setPreferredSize(new Dimension(200, 60));
//Panel Layouts
panel.setLayout(new BorderLayout());
center.setLayout(new GridLayout(5, 4, 2, 2));
//Add other panel elements
displayOutput.add(textArea);
panel.add(displayOutput, BorderLayout.NORTH);
panel.add(center, BorderLayout.CENTER);
//For some reason adding this makes the array of buttons appear
JButton btnNewButton = new JButton("1");
center.add(btnNewButton);
//Create buttons
for(int i = 0; i < 20; i++){
CalcButtons cButtons[] = new CalcButtons[20];
cButtons[i] = new CalcButtons();
//Add buttons to center box below output
center.add(cButtons[i]);
//Sets fourth column of buttons in cyan.
if(((i + 1) % 4) == 0){
cButtons[i].setBackground(Color.CYAN);
}
}
//Add panel to window
getContentPane().add(panel);
this.setVisible(true);
}
}
Container Class:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Container extends JPanel {
public Container() {
super();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
Button Class:
import javax.swing.*;
import java.awt.Color;
public class CalcButtons extends JButton
{
public CalcButtons()
{
this.setBackground(Color.WHITE);
this.setBorder(null);
}
}
This code then produced this:
However if I remove this:
//For some reason adding this makes the array of buttons appear
JButton btnNewButton = new JButton("1");
center.add(btnNewButton);
It produces this:
The problem is the size of your buttons are 0. You have set the border to null and there is no icon or text set. So when GridLayout calls getPreferredSize() on your buttons they return a size of 0,0 (width, height). When you add the JButton with a 1 in it then all of sudden one component has size. Since Gridlayout makes all components the same size you now can see your buttons. If you want your buttons to be blank but also be drawn set your border to an empty border with a size of 1 or greater on each edge.

Border Layout Spacing/Margins

for my beginner Java class we made an automated Tic-Tac-Toe game, and now we are creating a GUI to play it on. However, I'm having a lot of trouble getting the spacing/margins right. So far, I've just been trying to get the general framework for the GUI, and then I'm going to go back and actually implement the Tic-Tac-Toe game I have already made. So, far, I have this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ITTTGUI extends JFrame implements ActionListener{
//butimport javax.swing.border.*;tons
private JPanel sizePanel;
private JPanel buttonPanel;
private JPanel displayPanel;
private JPanel bottomPanel;
private JTextField size;
private JButton rebuildButton;
private JButton[] buttons;
private JLabel output;
//constructor
public NumberChooser(){
setTitle("BitchFace");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//content pane
Container cp = getContentPane();
//add a panel for the size
sizePanel = new JPanel();
sizePanel.setBorder(new EmptyBorder(5, 5, 5, 5) );//adds margin to panel
sizePanel.setLayout(new FlowLayout());
size = new JTextField("3",5);
sizePanel.add(new JLabel("N"));
sizePanel.add(size);
rebuildButton = new JButton("Rebuild");
rebuildButton.addActionListener(this);
sizePanel.add(rebuildButton);
//add bottom panel for output
sizePanel.add(new JButton("Player:"), BorderLayout.EAST);
sizePanel.add(new JButton("Move:"), BorderLayout.EAST);
sizePanel.add(new JButton("Winner:"), BorderLayout.EAST);
//add a panel for the numbers
buttonPanel = new JPanel();
buttonPanel.setBorder(new EmptyBorder(5, 5, 5, 5) );//adds margin to panel
buildButtonsPanel();
//add bottom panel for output
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(new EmptyBorder(5, 5, 5, 5) );//adds margin to panel
bottomPanel.add(new JButton("New Game"), BorderLayout.SOUTH);
bottomPanel.add(new JButton("Advise"), BorderLayout.SOUTH);
bottomPanel.add(new JButton("Quit"), BorderLayout.SOUTH);
//add panels to main pane
cp.setLayout(new BorderLayout());
cp.add(sizePanel, BorderLayout.EAST);
cp.add(buttonPanel, BorderLayout.CENTER);
cp.add(bottomPanel, BorderLayout.SOUTH);
pack();
}
//this is a helper method to rebuild the buttons panel
private void buildButtonsPanel(){
int n = 3;
try{
n = Integer.parseInt(size.getText());
}catch(Exception e){
e.printStackTrace();
}
buttonPanel.removeAll();
buttonPanel.setLayout(new GridLayout(n,n,4,4));
buttons = new JButton[n*n];
for(int i=0; i < buttons.length; i++){
buttons[i] = new JButton("*");
buttonPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
revalidate();
repaint();
pack();
}
public void actionPerformed(ActionEvent e){
Object s = e.getSource();
//check to see if the action came from the rebuild button
if(s == rebuildButton){
buildButtonsPanel();
}
//otherwise it came from the grid
}
//entry point
public static void main(String[] args){
//create the GUI
NumberChooser nc = new NumberChooser();
nc.setVisible(true);
}
}
It doesn't have to be exact, just generally the same.
And also there is no X or winner variable since I haven't implemented that. I also tried changing the margins from (5,5,5,5) to like (1,1,1,1), but that didn't change anything at all so that also confused me.
Any help with this, or how to generally go about this assignment would be appreciated.
(And it's not accepting my images. Sorry.)
Links are:
The problem is that is looks like this:
https://i1224.photobucket.com/albums/ee362/Devolutor/COPimage1_zps459f304b.png
And it is supposed to look like this:
http://i1224.photobucket.com/albums/ee362/Devolutor/COPimage2_zps8981c846.png
To have more space between the buttons, use a number of pixels beiiger than 4 for the grid layout:
buttonPanel.setLayout(new GridLayout(n,n,4,4));
To have a grid rather than a flow at the right side, use a GridLayout (just like you did for your buttons, but with 4 rows and 2 columns) rather than a FlowLayout.

Dynamic adding JPanel to another JPanel in Java Swing

I am very new for the java swing and so does java. I use netbeans' window's builder to design the GUI. I have a JPanel called orderListPanel which includes a JPanel called orderListRowPanel. Now, I got a list of JPanel and I want to insert these JPanels to the orderListPanel.
http://postimage.org/image/ex00whf69/
orderListPanel is in the middle and orderListRowPanel is just the same place like orderListPanel
http://postimage.org/image/dbrtn33sj/
right now I wanna insert many JPanels into orderListPanel and make it look like a list. The red squares are the components in side the JPanel.
I try to use BorderLayout and when I use
foreach loop orderListPanel.add(List pList), I can't see any result inside the orderListPanel. Do anybody know how to solve it?
Do not use Netbeans automated GUI builder. Drag and Drop GUI building technique is not acceptable in Java community. You have not provided the code so we can't do a code edit. Your images are not available.
But however, this is how you can do it. This is a pure hand code
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import java.util.List;
public class GUIBuilder extends JFrame
{
private JPanel orderList;
private JPanel orderListRow;
private JPanel additionalPanel;
private List panels = new ArrayList(); //Your List
private JLabel label1, label2, label3;
public GUIBuilder()
{
label1 = new JLabel("Label 1"); //Create the JLabels
label2 = new JLabel("Label 2");//Create the JLabels
label3 = new JLabel("Label 3");//Create the JLabels
orderList = new JPanel(); //Creating the orderList JPanel
orderList.setLayout(new BoxLayout(orderList, BoxLayout.Y_AXIS)); //Setting Box layout, and set the direction to Y axis.
orderListRow = new JPanel(); //Creating the orderListRow JPanel
orderListRow.add(label1);
additionalPanel = new JPanel(); //Creating the additionalPanel JPanel
additionalPanel.add(label2);
orderList.add(orderListRow); //Adding orderListRow into orderList
orderList.add(additionalPanel); //Adding additionalPanel into orderList
this.setLayout(new GridLayout(1,1));
this.add(orderList); //Setting orderList into JFrame
this.pack(); //Setting JFrame size. This will only take required space
this.setVisible(true); //Making JFrame Visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //When you hit the 'X' button, the program will exit
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //Setting the UI into your native platform UI
new GUIBuilder(); //Calling your program
}
catch(Exception e)
{
e.printStackTrace(); //If any error occured in setting up UI, print the stack trace
}
}
}
If you got the Panels inside a List, then use this
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import java.util.List;
public class GUIBuilder extends JFrame
{
private JPanel orderList;
private JPanel orderListRow;
private JPanel additionalPanel;
private List<JPanel> panels = new ArrayList<JPanel>(); //Your List
private JLabel label1, label2, label3;
public GUIBuilder()
{
label1 = new JLabel("Label 1"); //Create the JLabels
label2 = new JLabel("Label 2");//Create the JLabels
label3 = new JLabel("Label 3");//Create the JLabels
orderList = new JPanel(); //Creating the orderList JPanel
orderList.setLayout(new BoxLayout(orderList, BoxLayout.Y_AXIS)); //Setting Box layout, and set the direction to Y axis.
orderListRow = new JPanel(); //Creating the orderListRow JPanel
orderListRow.add(label1);
panels.add(orderListRow); // Add the panel to the List
additionalPanel = new JPanel(); //Creating the additionalPanel JPanel
additionalPanel.add(label2);
panels.add(additionalPanel); // Add the panel to the List
for(int i=0;i<panels.size();i++)
{
orderList.add(panels.get(i));
}
this.setLayout(new GridLayout(1,1));
this.add(orderList); //Setting orderList into JFrame
this.pack(); //Setting JFrame size. This will only take required space
this.setVisible(true); //Making JFrame Visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //When you hit the 'X' button, the program will exit
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //Setting the UI into your native platform UI
new GUIBuilder(); //Calling your program
}
catch(Exception e)
{
e.printStackTrace(); //If any error occured in setting up UI, print the stack trace
}
}
}

JTabbedPane JLabel, JTextField

Right, I have a JTabbedPane that has a JPanel that contains a JLabel and a JTextField.
my code
JTabbed Pane declaration :
this.tabPane = new JTabbedPane();
this.tabPane.setSize(750, 50);
this.tabPane.setLocation(10, 10);
tabPane.setSize(750,450);
tabPane.add("ControlPanel",controlPanel);
textfield declaration :
this.channelTxtFld = new JTextField("");
this.channelTxtFld.setFont(this.indentedFont);
this.channelTxtFld.setSize(200, 30);
this.channelTxtFld.setLocation(200, 10);
JLabel :
this.channelLabel = new JLabel("Channel name : ");
this.channelLabel.setSize(150, 30);
this.channelLabel.setLocation(10,10);
private void createPanels() {
controlPanel = new JPanel();
controlPanel.setSize(650,500);
}
private void fillPanels() {
controlPanel.add(channelLabel);
controlPanel.add(channelTxtFld);
}
So what my plan is, was to have a tabbed pane that has a JPanel where I have some Labels, textfields and buttons on fixed positions, but after doing this this is my result:
http://i.stack.imgur.com/vXa68.png
What I wanted was that I had the JLabel and next to it a full grown JTextfield on the left side not in the middle.
Anyone any idea what my mistake is ?
thank you :)
What kind of Layout Manager are you using for your controlPanel, you probably want BorderLayout, putting the Label in the West, and the TextField in the center.
BTW, setting the size and position of various components doesn't make sense unless you are using a Null Layout, which isn't a good idea. So i'd remove all that stuff and let the Layout Manager do it for you.
Use a LayoutManager and consider also the methods setPreferredSize, setMinimumSize, setMaximumSize to adjust components bounds according on which is your desired effect.
Assuming the default JPanel layout, FlowLayout, give the JTextField a non-zero number of columns, and give the JLabel a JLabel.LEFT constraint.
Addendum:
a full grown JTextField
Something like this?
import java.awt.*;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/5773874
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.setPreferredSize(new Dimension(400, 200));
jtp.addTab("Control", new MyPanel("Channel"));
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
private static class MyPanel extends JPanel {
private final JLabel label = new JLabel("", JLabel.LEFT);
private final JTextField text = new JTextField();
public MyPanel(String name) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
label.setText(name);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
this.add(label);
this.add(text);
}
}
}

Categories