BorderLayout, Impossible to set a manual Location - SWING Java - java

I'm having a problem, i implemented a BorderLayout JPanel. And if i try to move a button for a example in the North section, it'll stay at a default location.
Here's my code :
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time;
double temperature=0.0;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(700,400);
this.setLocationRelativeTo(null);
this.setResizable(true);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
ip = new JButton ("New");
ip.setPreferredSize(new Dimension(100,50));
ip.setLocation(0, 0);
north.add(ip);
print = new JButton ("Print");
north.add(print);
north.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("10",1,5);
north.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
north.add(start);
south = new JPanel();
legend = new JLabel("Legends are here");
south.add(legend);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
container.add(south, BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
}
I want for example my "New" button to be at the left top corner of my window by writing "ip.setLocation(0,0);"
Window
And it stays by default to the center..
Any ideas ?

Oracle Documentation about BorderLayout
A border layout lays out a container, arranging and resizing its
components to fit in five regions: north, south, east, west, and
center.
Solution
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
ip.setPreferredSize(new Dimension(100,50));
print = new JButton ("Print");
north.add(ip, BorderLayout.WEST);
JPanel centerPanel = new JPanel();
centerPanel.add(print);
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("10",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
The north panel is now composed of the following two parts :
ip (JButton) and centerPanel(JPanel) containing the rest of the components.
Output

What you're trying to do is use an AbsoluteLayout instead of a BorderLayout, BorderLayout uses Cardinal directions to set objects on the pane, such as North, East, South, West, and Center. You may want to look at the JavaDoc for BorderLayout.
As an example, you need to set your north panel to a BorderLayout()
north.setLayout(new BorderLayout());

Related

BoxLayout only showing last component added

Looked at some previous posts pertaining to my subject but too no avail.
Trying to align components using BoxLayout but I cannot get it to work. I have tinkered with it for some time now with different results but I can't figure it out. I have used the default FlowLayout with no problems, I am trying to learn and expand my knowledge and BoxLayout will be better for my program. I want everything to stay in alignment if the User resizes their application window. I've adjusted all the sizes this way after just trying to get it to work and failing.
package GUI;
import javax.swing.*;
import java.awt.*;
/**
* Created by Thunderfoot on 7/31/2016. Keep Growing!
* Graphical User Interface
* Needs 3 JPanels(Text area + scroll pane)(2 Buttons) (1 Button), a JTextArea, JScrollPane, and 3 JButtons
*/
public class PrimaryFrame extends JFrame {
//Class variables
private static JPanel panel1, panel2, panel3;
public static JTextArea output;
//Constructor
public PrimaryFrame() {
//Frame component attributes
final Dimension FRAME_SIZE = new Dimension(400, 400);
final Dimension PANEL1_SIZE = new Dimension(400, 250);
final Dimension PANEL2_SIZE = new Dimension(400, 40);
final Dimension PANEL3_SIZE = new Dimension(400, 40);
//JFrame is PrimaryFrame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(FRAME_SIZE);
setMaximumSize(FRAME_SIZE);
setTitle("Fighting Game");
//JPanel for Text
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.PAGE_AXIS));
panel1.setMinimumSize(PANEL1_SIZE);
panel1.setPreferredSize(PANEL1_SIZE);
panel1.setMaximumSize(PANEL1_SIZE);
panel1.setBackground(Color.BLACK);
//JPanel for Attack and Kick Buttons
panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.LINE_AXIS));
panel2.setMinimumSize(PANEL2_SIZE);
panel2.setPreferredSize(PANEL2_SIZE);
panel2.setMaximumSize(PANEL2_SIZE);
panel2.setBackground(Color.BLUE);
//JPanel for Power Attack Button
panel3 = new JPanel();
panel3.setLayout(new BoxLayout(panel3, BoxLayout.PAGE_AXIS));
panel3.setMinimumSize(PANEL3_SIZE);
panel3.setPreferredSize(PANEL3_SIZE);
panel3.setMaximumSize(PANEL3_SIZE);
panel3.setBackground(Color.ORANGE);
panel3.add(Box.createHorizontalGlue());
panel3.add(Box.createVerticalGlue());
//JTextArea & JScrollPane
output = new JTextArea();
output.setEditable(false);
JScrollPane outputScroller = new JScrollPane(output, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outputScroller.setMaximumSize(new Dimension(375, 250));
outputScroller.setBorder(BorderFactory.createLineBorder(Color.RED));
panel1.add(outputScroller);
panel1.add(Box.createHorizontalGlue());
panel1.add(Box.createVerticalGlue());
//Attack Button
JButton attackButton = new JButton(" ATTACK ");
attackButton.setMaximumSize(new Dimension(75, 30));
attackButton.setBorderPainted(true);
//Kick Button
JButton kickButton = new JButton(" KICK ");
kickButton.setMaximumSize(new Dimension(75, 30));
kickButton.setBorderPainted(true);
//Add components
panel2.add(attackButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
panel2.add(kickButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
//Power Attack Button
JButton powAttButton = new JButton(" POWER ATTACK ");
powAttButton.setMaximumSize(new Dimension(150, 30));
powAttButton.setBorderPainted(true);
panel3.add(powAttButton);
panel3.add(Box.createHorizontalGlue());
}
public void buildGUI() {
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
}
You have to set the Layout of your PrimaryFrame.
I suggest you add an additional line to your buildGUI() method:
public void buildGUI() {
//defines the Layout for the main Frame
this.setLayout(new GridLayout(3,1)) //its up to you wich Layout you use
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
Notice GridLayout(3,1) will generate a layout with three rows and one column

Adding a label to the center south of a panel?

The code below adds the label to the left south of the panel, and when I use set location with the label, the position does not change. Is there a way to make the label be in the center south of the panel without the need for an extra panel?
EDIT: the JFrame has a BorderLayout and adds the panel to CENTER
JPanel pnl = new JPanel();
pnl.setPreferredSize(new Dimension(500,500));
JLabel lbl = new JLabel("label");
pnl.setLayout(new BorderLayout());
pnl.add(lbl, BorderLayout.SOUTH);
It seem you need to set text align of label to center panel?
If so, try this:
JPanel pnl = new JPanel();
pnl.setPreferredSize(new Dimension(500, 500));
JLabel lbl = new JLabel("label", SwingConstants.CENTER); //Set text align
pnl.setLayout(new BorderLayout());
pnl.add(lbl, BorderLayout.SOUTH);
lbl.setBackground(Color.red);
lbl.setOpaque(true); //Test background
getContentPane().add(pnl);
Result:

Textarea maximalsize in Borderlayout

I have a simple problem but I found no good solution for it. I have a JFrame with components at SOUTH, NORTH, EAST, and CENTER. On CENTER is my problem. On center I have a JPanel with a Borderlayout and 2 JTextAreas (one on NORTH, one int the CENTER).
I want that the first panel begins always on top of the panel and stretch maximum (if needed) to the middle of the panel, not more. The second area should begin at the end of the first area. If one of both text areas is to big, there should appear a JScrollPane.
What is the best Way to realize that? Should I use a other layout for the panel?
Here is my little execute example for it:
public class myGUI {
public static void main(String[] args) {
new myGUI();
}
public myGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//Add Content at South, West and North....
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
centerPanel.add(new JScrollPane(new JTextArea("AREA")), BorderLayout.NORTH);
centerPanel.add(new JScrollPane(new JTextArea("AREA2")), BorderLayout.CENTER);
frame.add(centerPanel);
frame.setVisible(true);
}
}
Possible scenarios of the center panel:
SOLUTION with help from #Hovercraft Full Of Eels
public class MyGUI {
public static void main(String[] args) {
new MyGUI();
}
private static GridBagConstraints constraint = new GridBagConstraints();
public MyGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new JLabel("NORTH!"), BorderLayout.NORTH);
frame.add(new JLabel("EAST!"), BorderLayout.EAST);
frame.add(new JLabel("SOUTH!"), BorderLayout.SOUTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
changeConstraint(0,0);
JTextArea text1 = createTextArea("11111111111111");
centerPanel.add(text1, constraint);
changeConstraint(0,1);
JTextArea text2 = createTextArea("2222222222222");
centerPanel.add(text2, constraint);
JScrollPane scroll = new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frame.add(scroll, BorderLayout.CENTER);
frame.setVisible(true);
}
/**
* Create a Gridbag Constraint
* #param text
* #return
*/
private void changeConstraint(int gridx, int gridy){
constraint.anchor = GridBagConstraints.FIRST_LINE_START;
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.weighty = 0;
constraint.weightx = 1.0;
constraint.gridx = gridx;
constraint.gridy = gridy;
}
/**
* Create a Textarea
* #param text
* #return
*/
private JTextArea createTextArea(String text){
JTextArea textarea = new JTextArea(text);
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
return textarea;
}
}
One possibility: Consider creating a JPanel that uses GridBagLayout, and adding both JTextAreas to this JPanel, making sure to set their weightx to 0 and weighty to a non-zero value, say 1.0. Then place that JPanel into a JScrollPane and the JScrollPane into your GUI.

drag and drop of jcomponents in java in rum time

I can do this:
I have a JFrame with 2 JPanel objects. In the panel on the left, I want to put the components of Java Swing useful for the construction of an user interface. The panel on the right is empty.
On run-time, my user should to be able to copy with drag and drop drag from one panel to another the selected component. But the copied component on the right panel, can be moved or deleted.
I have created the panel, but I don't know if is better inserire the component as image, label or true component.. and how to make this possible..
This is my panel for the customization.. I have to insert the component in the JTabbedPane in the PanelSx..
public class Customize extends JFrame {
private JPanel panelSx, panelCx, panelMobile;
private JButton buttonSave;
private TabbedPaneComponents tpc;
public Customize(){
Container c = getContentPane();
c.setLayout(new BorderLayout());
setResizable(true);
setTitle("Design Preview");
setSize(800, 650);
setLocation(250,50);
panelSx = new JPanel();
panelSx.setPreferredSize(new Dimension(300, 200));
panelSx.setOpaque(true);
panelSx.setBackground(Color.RED.darker());
panelCx = new JPanel();
panelCx.setPreferredSize(new Dimension(200, 200));
panelCx.setOpaque(true);
panelCx.setBackground(Color.BLUE);
// display panel
panelMobile = new JPanel();
panelMobile.setPreferredSize(new Dimension(300,500));
panelMobile.setOpaque(true);
panelMobile.setBackground(Color.PINK.darker());
panelMobile.setFocusable(false);
buttonSave = new JButton("Save");
panelCx.add(panelMobile);
c.add(panelSx, BorderLayout.WEST);
c.add(panelCx, BorderLayout.CENTER);
tpc = new TabbedPaneComponents();
panelSx.add(tpc);
}
}
public class TabbedPaneComponents extends JTabbedPane{
private JPanel panel1,panel2,panel3;
public TabbedPaneComponents(){
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(200,300));
addTab("Form Widgets", panel1);
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(200,300));
addTab("Text Field", panel2);
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(200,300));
addTab("Other", panel3);
}
}
I would have to suggest using a JToolBar because of it's built in drag'n'drop features. I would put the component inside of the toolbar.

BorderLayout.CENTER "disappears"

I'm coding a prototype, but got problems with the GUI.
I want the JPanel pCustomer to be centered, but doing so it disappears completely. If I put it for example in the SOUTH, everything is fine.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JPanel implements ActionListener {
private JPanel pTop = new JPanel();
private JPanel pMenue = new JPanel();
private JPanel pContent = new JPanel();
private JPanel pCustomer = new JPanel();
private JPanel pEnq = new JPanel();
private JPanel pCustomerMenue = new JPanel();
private JTextField tf1 = new JTextField();
private JButton bCustomer = new JButton("Customer");
private JButton bEnq = new JButton("Product");
private JButton bCNew = new JButton("New Customer");
private JLabel lCustomer = new JLabel("Customer");
String[] customerString = {"--- SELECT -- ", "New Customer", "Edit Customer", "Delete Customer"};
private JComboBox cb1 = new JComboBox(customerString);
private JLabel lRes = new JLabel();
String[] productString = {"--- SELECT -- ", "Sell Product", "Enquire Product", "Complain Product"};
private JLabel lWelcome = new JLabel("Welcome to our System!");
private JLabel lNo = new JLabel("Customer Number: ");
private JLabel lEnq = new JLabel("Enquiry");
public Test() {
this.setLayout(new BorderLayout());
// pTop
this.add(pTop, BorderLayout.NORTH);
pTop.setLayout(new BorderLayout());
pTop.add(lNo, BorderLayout.WEST);
pTop.add(tf1, BorderLayout.CENTER);
// pMenue
this.add(pMenue, BorderLayout.WEST);
pMenue.setLayout(new GridLayout(5, 1));
pMenue.add(bCustomer);
pMenue.add(bEnq);
// pContent
this.add(pContent, BorderLayout.CENTER);
pContent.add(lWelcome);
pContent.setLayout(new BorderLayout());
pContent.setBackground(Color.GREEN);
// pCustomer
pContent.add(pCustomer, BorderLayout.CENTER); // EAST, SOUTH, WEST works, but I want it to be centered.
pCustomer.add(cb1);
pCustomer.add(lRes);
pCustomer.setVisible(false);
pCustomer.setBackground(Color.blue);
// pCustomerMenue
pContent.add(pCustomerMenue, BorderLayout.NORTH);
pCustomerMenue.add(bCNew);
pCustomerMenue.setVisible(false);
pCustomerMenue.setBackground(Color.red);
// pEnq
pContent.add(pEnq, BorderLayout.CENTER);
pEnq.add(lEnq);
pEnq.setVisible(false);
// ---
bCustomer.addActionListener(this);
bEnq.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
lWelcome.setVisible(false);
if (source == bCustomer) {
init();
pCustomer.setVisible(true);
pCustomerMenue.setVisible(true);
bCustomer.setEnabled(false);
}
if (source == bEnq) {
init();
pEnq.setVisible(true);
bEnq.setEnabled(false);
}
}
public void init() {
pCustomer.setVisible(false);
pCustomerMenue.setVisible(false);
pEnq.setVisible(false);
bCustomer.setEnabled(true);
bEnq.setEnabled(true);
}
}
If I remove these 3 lines:
pContent.add(pEnq, BorderLayout.CENTER);
pEnq.add(lEnq);
pEnq.setVisible(false);
I can even put it in the Centre and it works.
Read up about border layout. Basically you have 5 positions (NORTH, EAST, SOUTH, WEST, CENTER) and whenever you put a component into one of those positions any component already in that position is replaced.
Thus pContent.add(pEnq, BorderLayout.CENTER); will replace pCustomer with pEnq.
If you want both panels in the center you either need to put an intermediate panel into the center and then add the other panels to that one or use another layout manager, e.g. MiGLayout.
With MiGLayout your pContent layout might look like this:
pContent.setLayout(new MiGLayout());
pContent.add(pCustomerMenue, "pushx, wrap"); //fill the available width, new line after this component
pContent.add(pCustomer, "pushx, wrap"); //fill the available width, new line after this component
pContent.add(pEnq, "pushx"); //fill the available width
You try to add two different Panels to the Center of the BorderLayout.
First you add
pContent.add(pCustomer, BorderLayout.CENTER); // EAST, SOUTH, WEST works, but I want it to be centered.
And a few Lines later you do:
pContent.add(pEnq, BorderLayout.CENTER);
So pEnq lays over pCustomer!

Categories

Resources