Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8249557
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T23:35:12+00:00 2026-06-07T23:35:12+00:00

I’m new to layouts and what I’m using now is a CardLayout with two

  • 0

I’m new to layouts and what I’m using now is a CardLayout with two different cards that currently have a background image painted on and a button. As seen below, the button is at the top of the screen and I’d like to position it somewhere closer to the bottom. My understanding is that a GridBagLayout would be the best way to accomplish that. So my first question is, is that true? And also, is it possible to do so if the JPanel I want to put the GridBagLayout on is a card in a CardLayout. I’d like to put many other objects into the GridBagLayout (if that’s the best way to do it and if it’s possible) as I get further into the project, so any advice on where the right direction to go would be greatly appreciated.

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Cards implements ActionListener {    
private JPanel cards;
private JButton button1;
private JButton button2;
private Image backgroundImage;

public void addComponentToPane(Container pane) throws IOException {
    try {           
        backgroundImage = ImageIO.read(getClass().getResource("resources/background.jpg"));         
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    }

    //create cards
    JPanel card1 = new JPanel()
    {
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.drawImage(backgroundImage, 0, 0, null);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(
                    backgroundImage.getWidth(null),
                    backgroundImage.getHeight(null));
        }
    };
    JPanel card2 = new JPanel()
    {
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.drawImage(backgroundImage, 0, 0, null);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(
                    backgroundImage.getWidth(null),
                    backgroundImage.getHeight(null));
        }
    };
    //create buttons
    button1 = new JButton("Button 1");
    button2 = new JButton("Button 2");
    button1.addActionListener(this);
    button2.addActionListener(this);
    //add buttons to cards
    card1.add(button1);        
    card2.add(button2);
    //create panel that contains cards
    cards = new JPanel(new CardLayout());
    cards.add(card1, "Card 1");
    cards.add(card2, "Card 2");
    pane.add(cards, BorderLayout.SOUTH);        
}

public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
}

public static void createAndShowGUI() throws IOException  {
    //create and setup window
    JFrame frame = new JFrame("Frame"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    //create and setup content pane
    Cards main = new Cards();
    main.addComponentToPane(frame.getContentPane());        
    //display window
    frame.pack();       
    //frame.setResizable(false);
    frame.setVisible(true);
}

public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == button1) {
        CardLayout cl = (CardLayout) (cards.getLayout());
        cl.show(cards, "Card 2");     
    } else if (ae.getSource() == button2) {
        CardLayout cl = (CardLayout) (cards.getLayout());
        cl.show(cards, "Card 1");
    }        
}            

public static void main(String[] args) {
    //set look and feel
    try {
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }                

    //schedule job for the event dispatch thread creating and showing GUI        
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {                   
                    try {
                        createAndShowGUI();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                
        }
    });     
}   
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T23:35:14+00:00Added an answer on June 7, 2026 at 11:35 pm

    a GridBagLayout will do what you want, yes. It’s one of the most flexible (but also one of the most complex) LayoutManagers available. Whether or not it’s the “best” way to do it depends on what other controls you want to add to your panel, whether or not you want them to resize, what you want to happen when the parent JPanel is resized, and other factors.

    re: nesting JPanels with different layouts, yes. It’s perfectly fine to have a JPanel with a GridBagLayout inside of a JPanel with a CardLayout inside of a JPanel with a BorderLayout [etc…]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a jquery bug and I've been looking for hours now, I can't
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I want use html5's new tag to play a wav file (currently only supported
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have thousands of HTML files to process using Groovy/Java and I need to
I have two tables with like below codes: Table: Accounts id | username |

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.