I am using gridbaglayout to show a JLabel (number of thumbnails ) and some thumbnails whenever I add the thumbnail to the Jpanel with gridbaglayout it shows up in the center ignoring gridy values. The gridx values are working correctly but gridy values are completely ignored...
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
public class grid {
private JFrame frame = new JFrame();
private JLabel a = new JLabel("Welcome to PhotoAlbum55");
/**
* Create the frame.
*/
public grid() {
createAndShowGUI();
}
private void addComponentsToPane(Container pane) {
SpringLayout layout = new SpringLayout();
pane.setLayout(layout);
layout.putConstraint(SpringLayout.WEST, a, 60, SpringLayout.WEST, pane);
layout.putConstraint(SpringLayout.NORTH, a, 0, SpringLayout.NORTH, pane);
a.setFont(new Font("Segoe UI", Font.BOLD, 20));
pane.add(a);
JPanel photoPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
photoPanel.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
JScrollPane photoScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
photoScroll.setViewportView(photoPanel);
pane.add(photoScroll);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 15;
gbc.fill = GridBagConstraints.HORIZONTAL;
JLabel photo = new JLabel();
Image img = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg").getImage();
Image newimg = img.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);
photo.setIcon(newIcon);
gbl.setConstraints(photo, gbc);
photoPanel.add(photo);
JLabel photo1 = new JLabel();
Image img1 = new ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Lighthouse.jpg").getImage();
Image newimg1 = img1.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon1 = new ImageIcon(newimg1);
photo1.setIcon(newIcon1);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.ipadx = 15;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbl.setConstraints(photo1, gbc);
photoPanel.add(photo1);
// photoPanel.setPreferredSize(new Dimension(900, 900));
photoScroll.setPreferredSize(new Dimension(500, 500));
layout.putConstraint(SpringLayout.WEST, photoScroll, 60, SpringLayout.WEST, a);
layout.putConstraint(SpringLayout.NORTH, photoScroll, 100, SpringLayout.NORTH, a);
}
private void createAndShowGUI() { // Creating the GUI...
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("PhotoAlbum55");
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setSize(690, 622);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new grid();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Both images are on the same y co-ordinate so the application is behaving as intended. On the other hand, the x co-ordinates differ so you need to set
gbc.weightx = 1;
for them to be positioned. If you need to add images to the top of the panel, they will need to be anchored there and set the weight along the y axis:
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
Related
I had created this view by using null layout:
This is the Code i had used to create above layout
public class Page1311 extends JPanel {
// private JTable table;
// public JScrollPane pane=null;
public JPanel panel=null;
public JButton back=null;
/**
* Create the panel.
*/
public Page1311() {
setLayout(null);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
List<List<String>> list=new ArrayList<List<String>>();
for(int j=0;j<=5;j++)
{
List<String> list1=new ArrayList<>();
list1.add("Honda Showroom"+j);
list1.add("Mandsaur");
list1.add("25 Chakrawati Colony Railway Station Road");
list1.add("Activa");
list1.add("2017");
list1.add("Honda");
list.add(list1);
}
getLayout(list,this);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
}
public static void getLayout(List<List<String>> list,JPanel pane)
{
int i=0;
int x=100;
int y=100;
int height=20;
int width=200;
int size=list.size();
JLabel[] lblSName=new JLabel[size];
JLabel[] lblSAddress=new JLabel[size];
JLabel[] lblSCity=new JLabel[size];
JLabel[] lblVName=new JLabel[size];
JLabel[] lblVVersion=new JLabel[size];
JLabel[] lblVCompanies=new JLabel[size];
JButton[] lblGo=new JButton[size];
Iterator<List<String>> it=list.iterator();
while(it.hasNext())
{
System.out.println(x+" "+y+" "+width+" "+height+" "+i);
Iterator iit=it.next().iterator();
lblSName[i]= new JLabel();
lblSName[i].setText("Name:"+iit.next());
lblSName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
lblSName[i].setBounds(x,y,width,height);
pane.add(lblSName[i]);
lblSCity[i] = new JLabel();
lblSCity[i].setText("City:"+iit.next());
lblSCity[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+" "+width+" "+height+" "+i);
lblSCity[i].setBounds(x+240,y,width,height);
pane.add(lblSCity[i]);
lblSAddress[i]= new JLabel();
lblSAddress[i].setText("Address:"+iit.next());
lblSAddress[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+y+" "+(width+256)+" "+height+" "+i);
lblSAddress[i].setBounds(x+470,y, width+256, height);
pane.add(lblSAddress[i]);
lblVName[i]= new JLabel();
lblVName[i].setText("Vehicle Name:"+iit.next());
lblVName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println(x+" "+(y+35)+" "+width+" "+height+" "+i);
lblVName[i].setBounds(x,y+35,width, height);
pane.add(lblVName[i]);
lblVVersion[i] = new JLabel();
lblVVersion[i].setText("Vehicle Version:"+iit.next());
lblVVersion[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+35+" "+width+" "+height+" "+i);
lblVVersion[i].setBounds(x+240,y+35, width, height);
pane.add(lblVVersion[i]);
lblVCompanies[i]= new JLabel();
lblVCompanies[i].setText("Vehicle Companies:"+iit.next());
lblVCompanies[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+(y+35)+" "+(width+256)+" "+height+" "+i);
lblVCompanies[i].setBounds(x+470,y+35, width+256,height);
pane.add(lblVCompanies[i]);
lblGo[i]= new JButton("Go ");
lblGo[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 15));
System.out.println(x+" "+(y+70)+" "+(width-130)+" "+height+" "+i);
lblGo[i].setBounds(x,y+70,width-130, height);
pane.add(lblGo[i]);
i++;
y=y+160;
System.out.println("new height"+y);
}
}
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.add(new Page1311());
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.setLocation(0, 0);
frame.setVisible(true);
}
}
But now i found that i cant use jscrollpane with null layout manager.So i want to create same layout by using any other layout manager.Can any one please help with with this or you can provide me any other way to use jscrollpane with null layout manager.
Thanks in advance
I'd use a combination of a GridBagLayout for each 'show room' panel, then a single column GridLayout panel to stack the collection of show room panels in a single container. The second panel would go in the scroll pane.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ShowRoomLayout {
private JComponent ui = null;
ShowRoomLayout() {
initUI();
}
private JPanel getShowRoomPanel(int num) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new TitledBorder("GridBagLayout"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
p.add(new JLabel("Name:Honda Showroom" + num), gbc);
gbc.gridx = 1;
p.add(new JLabel("City:Mandsaur"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Address:25 Chakrawati Colony Railway Station Road"), gbc);
gbc.gridy = 1;
gbc.gridx = 0;
p.add(new JLabel("Vehicle Name:Activa"), gbc);
gbc.gridx = 1;
p.add(new JLabel("Vehicle Version:2017"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Vehicle Companies:Honda"), gbc);
gbc.gridy = 2;
gbc.gridx = 0;
p.add(new JButton("Go"), gbc);
return p;
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel pList = new JPanel(new GridLayout(0, 1, 3, 3));
pList.setBorder(new TitledBorder("GridLayout"));
for (int ii = 1; ii < 21; ii++) {
pList.add(getShowRoomPanel(ii));
}
JScrollPane scrollPane = new JScrollPane(pList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ui.add(scrollPane);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ShowRoomLayout o = new ShowRoomLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
Dimension d = f.getSize();
f.setSize(new Dimension(d.width, 400));
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
JScrollPane has its own layout: ScrollPaneLayout. If you want to use any other, you don't set it on the scroll pane itself, you put a JPanel inside it and set the layout on that panel.
Another way without the need to set any layout manager for the JScrollPane is the method
JScrollPane.setViewportView(Component);
This is my preferred way. No size or layout handling on the fly.
If you want to place several Components to the same JScrollPane, just put a JPanel in between. The JPanel can have your preferred Layout.
If your layout uses a null layout manager, you need to tell the scroll pane the size of your component
JPanel pane = new JPanel(){
Dimension d = new Dimension(400, 400);
#Override
public Dimension getMinimumSize(){
return d;
}
#Override
public Dimension getPreferredSize(){
return d;
}
#Override
public Dimension getMaximumSize(){
return d;
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fill3DRect(25, 25, 350, 350, true);
}
};
pane.setLayout(null);
JFrame frame = new JFrame("check");
frame.setSize(200, 200);
frame.add(new JScrollPane(pane));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For this, I set the size of the pane to be 400, 400. The scroll pane will respect this. If you comment out the overriden methods, you'll see the scroll doesn't work anymore.
For OP to apply this technique they would just have to change the line where they add the panel to the JFrame.
frame.add(new JScrollPane(new Page1311()));
Since Page1311 doesn't use a layout manager then they need to override, getMin/Max/Preferred. as I did in my example. That would wrap the custom JPanel with a scroll pane, and the content would be scrollable.
OK I'm trying to modify an existing answer from below link to fit my needs. In my case I need to set the JTabbedPane.TOP, but then the buttons disappear.
I'm not too familiar with Swing, so someone please let me know. Below is the full working code example from link.
How to place components beneath tabs in right oriented JTabbedPane
public class RightTabPaneButtonPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RightTabPaneButtonPanel().makeUI();
}
});
}
public void makeUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabPlacement(JTabbedPane.TOP);
JPanel panel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < 3; i++) {
JPanel tab = new JPanel();
tab.setName("tab" + (i + 1));
tab.setPreferredSize(new Dimension(400, 400));
tabbedPane.add(tab);
JButton button = new JButton("B" + (i + 1));
button.setMargin(new Insets(0, 0, 0, 0));
panel.add(button);
}
JFrame frame = new JFrame();
frame.add(tabbedPane);
frame.pack();
Rectangle tabBounds = tabbedPane.getBoundsAt(0);
Container glassPane = (Container) frame.getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
int margin = tabbedPane.getWidth() - (tabBounds.x + tabBounds.width);
gbc.insets = new Insets(0, 0, 0, margin);
gbc.anchor = GridBagConstraints.SOUTHEAST;
panel.setPreferredSize(new Dimension((int) tabBounds.getWidth() - margin,
panel.getPreferredSize().height));
glassPane.add(panel, gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Here is an approach that uses the OverlayLayout:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TabbedPaneWithComponent
{
private static void createAndShowUI()
{
JPanel panel = new JPanel();
panel.setLayout( new OverlayLayout(panel) );
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("1", new JTextField("one"));
tabbedPane.add("2", new JTextField("two"));
tabbedPane.setAlignmentX(1.0f);
tabbedPane.setAlignmentY(0.0f);
JCheckBox checkBox = new JCheckBox("Check Me");
checkBox.setOpaque( false );
checkBox.setAlignmentX(1.0f);
checkBox.setAlignmentY(0.0f);
JPanel right = new JPanel( new FlowLayout(FlowLayout.RIGHT, 5, 0) );
right.setOpaque( false );
right.setAlignmentX(1.0f);
right.setAlignmentY(0.0f);
right.add( new JCheckBox("Check Me") );
right.add( new JCheckBox("Or Check Me") );
right.setMaximumSize( right.getPreferredSize() );
panel.add( checkBox );
// panel.add( right );
panel.add(tabbedPane);
JFrame frame = new JFrame("TabbedPane With Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setLocationByPlatform( true );
frame.setSize(400, 100);
frame.setVisible( true );
System.out.println(checkBox.getPreferredSize() + " : " + right.getPreferredSize());
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I guess this is what you want:
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.NORTHEAST;
panel.setPreferredSize(new Dimension(panel.getPreferredSize().width,
(int) tabBounds.getHeight()));
glassPane.add(panel, gbc);
So I'm trying to copy the layout of this website.
Website Pinterest Log In
Here's some what I have already done.
I'm using "null" for my layout.
I also put an actionlistener on my button which shows another frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Frame {
public static void main (String [] args) {
JFrame frame = new JFrame("Pinterest");
frame.setVisible(true);
frame.setSize(1300,750);
JPanel panel = new JPanel();
frame.add(panel);
JLabel name = new JLabel("Log in to Pinterest");
name.setBounds(500, 96, 300, 100);
name.setFont(new Font("Tahoma", Font.PLAIN, 28));
JTextField text1 = new JTextField(15);
text1.setBounds(500, 450, 300, 40);
JTextField text2 = new JTextField(15);
text2.setBounds(500, 350, 300, 40);
JButton button = new JButton("Log In");
button.setBounds(560,550, 200,30 );
panel.setLayout(null);
panel.add(name);
panel.add(text1);
panel.add(text2);
panel.add(button);
button.addActionListener(new Action1());
}
static class Action1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFrame frame2= new JFrame("Pinterest");
frame2.setVisible(true);
frame2.setSize(1300,750);
}}
Every time I would run this in my JCreator it would only show my frame. Then I have to maximize it to view the components but after I maximize it then minimize it doesn't hide anymore.
After I maximize the frame.
What is wrong with my code?
Does my code works on yours smoothly? does it shows?
How can I hide the first frame after clicking the button?
I'm having a hard time putting icon on the frame too.
Thanks for the help.
There are a number of basic mistakes
null layouts. Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Making the frame visible before you've finished updating the UI. In most cases this can be fixed with revalidate, but since that causes the layout managers to recalculate their layouts, it's pointless when you're using null layouts
The simple answer is, use layout managers. The longer answer is more complicated.
You have three distinct areas, the "login with" group, the "field" group and (what I like to term) the "action" group. Each of these have there own requirements and functionality, it's best to try a seperate them if you can.
This will allow to apply functionality to each group or class which is unique to that group/class and reduce a lot of management head aches
The following examples focus on the layout, it does not focus on how you would then connect the functionality, this would be achieved simply through the use of an Observer Pattern, perhaps like ActionListener
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LoginPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class LoginPane extends JPanel {
public LoginPane() {
setBackground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 20, 4, 20);
JLabel title = new JLabel("Log in to Pinterest");
title.setFont(title.getFont().deriveFont(Font.BOLD, 18f));
title.setBorder(new EmptyBorder(10, 0, 10, 0));
add(title, gbc);
add(new GroupPane(), gbc);
gbc.insets = new Insets(4, 0, 4, 0);
add(new JSeparator(JSeparator.HORIZONTAL), gbc);
gbc.insets = new Insets(4, 20, 4, 20);
add(new FieldPane(), gbc);
gbc.insets = new Insets(4, 0, 0, 0);
add(new ActionPane(), gbc);
}
}
public class GroupPane extends JPanel {
public GroupPane() {
setOpaque(false);
JPanel fbPane = new JPanel();
JPanel goPane = new JPanel();
JPanel twPane = new JPanel();
fbPane.setBackground(Color.RED);
goPane.setBackground(Color.BLUE);
twPane.setBackground(Color.CYAN);
fbPane.add(makeLabel("Log in with Facebook"));
goPane.add(makeLabel("Log in with Google"));
twPane.add(makeLabel("Log in with Twitter"));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 0, 4, 0);
add(fbPane, gbc);
add(goPane, gbc);
add(twPane, gbc);
}
protected JLabel makeLabel(String text) {
JLabel label = new JLabel(text);
label.setForeground(Color.WHITE);
label.setFont(label.getFont().deriveFont(Font.BOLD, 14f));
return label;
}
}
public class FieldPane extends JPanel {
private JTextField email;
private JPasswordField password;
public FieldPane() {
setOpaque(false);
email = new JTextField(10);
password = new JPasswordField(10);
email.setBackground(new Color(225, 225, 225));
password.setBackground(new Color(225, 225, 225));
Font font = email.getFont().deriveFont(Font.PLAIN, 24f);
email.setFont(font);
password.setFont(font);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 0, 4, 0);
add(email, gbc);
add(password, gbc);
JLabel label = new JLabel("Are you a business? Get started here");
label.setFont(label.getFont().deriveFont(Font.PLAIN, 10f));
gbc.insets.left = 4;
add(label, gbc);
}
}
public class ActionPane extends JPanel {
public ActionPane() {
setBorder(new EmptyBorder(10, 20, 10, 20));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.WEST;
add(makeLabel("Forgot your password?"), gbc);
gbc.gridy++;
add(makeLabel("Sign up now"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.ipady = 10;
gbc.anchor = GridBagConstraints.EAST;
JButton login = new JButton("Log in");
add(login, gbc);
}
protected JLabel makeLabel(String text) {
JLabel label = new JLabel(text);
label.setForeground(Color.DARK_GRAY);
return label;
}
}
}
Take a look at Laying Out Components Within a Container and How to Use GridBagLayout. The LoginPane could also make use of a GridLayout, see for more details
How can I put a button in the right place ?
My code:
import java.applet.*;
import java.awt.*;
public class Banner extends Applet {
int x, y;
Button button1 = new Button("Try!");
public void init() {
setSize(1200, 500);
setLayout(new BorderLayout()); //also I tried FlowLayout..
//button1.setBounds(500, 250, 25, 50); // not worked..
add("East", button1);
button1.addActionListener(this);
}
public void start() {
}
public void paint(Graphics g) {
}
}
For example I have few labels and images in my Applet. And I want put the button somewhere..
And also I want to set size the button, but method setSize() and method setBounds() isn't worked..
Have you tried?
add(button1,BorderLayout.EAST);
you can try GridBagLayout if there are multiple components
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTH;
Image image = ImageIO.read(new File("resources/Tulips.jpg"));
JLabel label = new JLabel(new ImageIcon(image));
JButton button1 = new JButton("Try!");
gc.gridx = 0;
gc.insets = new Insets(5, 5, 5, 5);
add(label, gc);
gc.insets = new Insets(50, 5, 5, 50);
gc.gridx = 1;
add(button1, gc);
You can try it with BorderLayout also by just adding button in new JPanel
Image image = ImageIO.read(new File("resources/Tulips.jpg"));
JLabel label = new JLabel(new ImageIcon(image));
setLayout(new BorderLayout(10,10));
add(label, BorderLayout.CENTER);
JPanel panel=new JPanel(new FlowLayout(FlowLayout.CENTER,50,10));
JButton button1 = new JButton("Try!");
panel.add(button1);
add(panel, BorderLayout.EAST);
I've attached a screenshot for which the following Border legend applies:
Yellow = JPanel with BorderLayout
Blue = JPanel with GridBagLayout
Fuchsia = JPanel with FlowLayout
There are two panels not blocked out in colors that warrant mentioning:
1) The title panel where the word "Primary" is displayed; this panel is at BorderLayout.NORTH in "Yellow" panel.
2) The image panel where the image of the device is located; this panel is a sibling to "Fuchsia"
"Blue" is at BorderLayout.CENTER in "Yellow" while "Fuchsia" and the image panel are given the following constraints:
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(0, 10, 0, 0);
c.fill = GridBagConstraints.BOTH;
//"Blue".add(imagePanel, c);
c.weighty = 0.80;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
//"Blue".add("Fuchsia", c);
As you can probably tell from the image, I'm trying to get rid of the "wasted" space in "Blue" right below "Fuchsia". I don't seem to be able to do it with GridBagConstraints, so am I just using the wrong LayoutManager? It looks to me like "Blue", who is at CENTER in the BorderLayout is just giving each child JPanel half of the available space and reserving the remainder space instead of contracting upward. What am I missing here? Is this simply a matter of setting a preferred or maximum size on "Fuchsia"? it doesn't seem like that will get me where I want to be, since the border around "Fuchsia" (which is covered by my color coding) is where I want the end of the component to be.
Have a look at this output, from this code example :
import java.awt.*;
import javax.swing.*;
public class LayoutTest
{
private void displayGUI()
{
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.YELLOW);
contentPane.setLayout(new BorderLayout(2, 2));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel headingLabel = new JLabel("Primary");
topPanel.add(headingLabel);
contentPane.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.BLUE);
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
JPanel imagePanel = new JPanel();
JLabel imageLabel = null;
try
{
imageLabel = new JLabel(
new ImageIcon(
new java.net.URL(
"http://pscode.org/"
+ "tame/screenshot/"
+ "landscape/slider1.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
imagePanel.add(imageLabel);
centerPanel.add(imagePanel, gbc);
JPanel detailsPanel = new JPanel();
detailsPanel.setOpaque(true);
detailsPanel.setBackground(Color.WHITE);
detailsPanel.setBorder(
BorderFactory.createEmptyBorder(
5, 5, 5, 5));
detailsPanel.setLayout(new GridLayout(0, 1, 5, 5));
JLabel statusLabel = new JLabel("Chassis Status : ");
JLabel usageLabel = new JLabel("Bandwidth Usage : ");
JLabel fanLabel = new JLabel("Fan Status : ");
detailsPanel.add(statusLabel);
detailsPanel.add(usageLabel);
detailsPanel.add(fanLabel);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.8;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 3;
centerPanel.add(detailsPanel, gbc);
contentPane.add(centerPanel, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutTest().displayGUI();
}
});
}
}
Without using GridBagLayout could be
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel yellowNorthPanel = new JPanel();
private JPanel yellowPanel = new JPanel();
private JPanel bluePanel = new JPanel();
private JPanel fuchsiaTopPanel = new JPanel();
private JPanel fuchsiaBottonPanel = new JPanel();
public NestedLayout() {
yellowNorthPanel.setBorder(new LineBorder(Color.yellow, 5));
yellowPanel.setLayout(new BorderLayout());
yellowPanel.setBorder(new LineBorder(Color.yellow, 5));
bluePanel.setLayout(new BorderLayout(5, 5));
bluePanel.setBorder(new LineBorder(Color.blue, 5));
fuchsiaTopPanel.setBorder(new LineBorder(Color.cyan, 5));
fuchsiaBottonPanel.setBorder(new LineBorder(Color.cyan, 5));
bluePanel.add(fuchsiaTopPanel, BorderLayout.NORTH);
bluePanel.add(fuchsiaBottonPanel);
yellowPanel.add(bluePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(yellowNorthPanel, BorderLayout.NORTH);
frame.add(yellowPanel);
//frame.pack();
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new NestedLayout();
}
});
}
}