0

This is a java template i found about Card Layout

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Main {

    private static final String CARD_JBUTTON =  "Card JButton";
    private static final String CARD_JTEXTFIELD = "Card JTextField";    
    private static final String CARD_JRADIOBUTTON = "Card JRadioButton";

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Card Layout Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // This JPanel is the base for CardLayout for other JPanels.
        final JPanel contentPane = new JPanel();
        contentPane.setLayout(new CardLayout(200, 200));

        /* Here we be making objects of the Window Series classes
         * so that, each one of them can be added to the JPanel 
         * having CardLayout. 
         */
        Window1 win1 = new Window1();
        contentPane.add(win1, CARD_JBUTTON);
        Window2 win2 = new Window2();
        contentPane.add(win2, CARD_JTEXTFIELD);
        Window3 win3 = new Window3();
        contentPane.add(win3, CARD_JRADIOBUTTON);

        /* We need two JButtons to go to the next Card
         * or come back to the previous Card, as and when
         * desired by the User.
         */
        JPanel buttonPanel = new JPanel(); 
        final JButton previousButton = new JButton("PREVIOUS");
        previousButton.setBackground(Color.BLACK);
        previousButton.setForeground(Color.WHITE);
        final JButton nextButton = new JButton("NEXT");
        nextButton.setBackground(Color.RED);
        nextButton.setForeground(Color.WHITE);

        buttonPanel.add(previousButton);
        buttonPanel.add(nextButton);

        /* Adding the ActionListeners to the JButton,
         * so that the user can see the next Card or
         * come back to the previous Card, as desired.
         */
        previousButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {   
                CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                cardLayout.previous(contentPane);
            }
        });
        nextButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                cardLayout.next(contentPane);   
            }
        });

        // Adding the contentPane (JPanel) and buttonPanel to JFrame.
        frame.add(contentPane, BorderLayout.CENTER);
        frame.add(buttonPanel, BorderLayout.PAGE_END);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

And this is my Window1.java

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;



class Window1 extends JPanel
{
    /*
     * Here this is our first Card of CardLayout, which will
     * be added to the contentPane object of JPanel, which
     * has the LayoutManager set to CardLayout.
     * This card consists of Two JButtons.
     */  
    private ActionListener action;

    public Window1() 
    {
        init();
    }

    private void init() 
    {
        final JButton clickButton = new JButton("Click ME");
        final JButton dontClickButton = new JButton("DON\'T CLICK ME");     

        final JTextField title = new JTextField(12);

        action = new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                if (ae.getSource() == clickButton)
                {
                    String myString = title.getText();
                    System.out.println(myString);
                }
                else if (ae.getSource() == dontClickButton)
                {
                    JOptionPane.showMessageDialog(null, "I told you not to click me!"
                                                        , "Wrong Button", JOptionPane.PLAIN_MESSAGE);
                }
            }
        };

        clickButton.addActionListener(action);
        dontClickButton.addActionListener(action);

        add(clickButton);
        add(dontClickButton);
        add(title);

    }
}

Now my problem is that how do i set the position of the textfields and buttons in Window1?

With this code they are set in the center of the view aligned horizontally.

I tried to use title.setLocation(5,5); but it's not working. Any suggestions?

cafebabe1991
  • 4,928
  • 2
  • 34
  • 42
r4id4
  • 5,877
  • 8
  • 46
  • 76

1 Answers1

2

Now my problem is that how do i set the position of the textfields and buttons in Window1? Rows like Jlabel - JTextField then new row ,and in the end of the page the button

The thing is you're not using any layout managers. The default layout manager for JPanel is FlowLayout, which will do exactly what you're experiencing (horizontal layout of the components).

Getting vertical alignment could be achieved by using different layout managers. You could use a GridBagLayout for all the component, or a GridLayout, or you could nest JPanel with different layout managers. The possibilities are endless. It just comes down to the exact look you want.

See Laying out Components Within a Container to learn how to use different layout managers. I'll give you an example, but don't let it stop you from looking at the tutorials. You need to learn them.

Also besides just positioning of the components layout managers use dynamic sizing either by respecting the preferred of components are not respecting them. You can see a picture in this answer of some of the layout managers that do and don't respect preferred sizes.

enter image description here

import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class LayoutManagers extends JPanel{

    public LayoutManagers() {
        JLabel label = new JLabel("Text Field");
        JTextField textField = new JTextField(20);
        JRadioButton rb1 = new JRadioButton("Radio 1");
        JRadioButton rb2 = new JRadioButton("Radio 2");
        JButton button = new JButton("Button");

        JPanel panel1 = new JPanel();
        panel1.add(label);
        panel1.add(textField);

        JPanel panel2 = new JPanel();
        panel2.add(rb1);
        panel2.add(rb2);

        JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        panel3.add(button);

        JPanel panel4 = new JPanel(new GridLayout(3, 1));
        panel4.add(panel1);
        panel4.add(panel2);
        panel4.add(panel3);

        setLayout(new GridBagLayout());
        add(panel4);     
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new LayoutManagers());
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thank you for your answer! What you mean is that i could use the first part of your code (out of the main) in my multiple Windows, while setting the swingUtilities... just once in the main right? – r4id4 Feb 24 '14 at 15:27
  • Pretty much. If you want this exact layout, everything in my constructor can be put into your constructor – Paul Samsotha Feb 24 '14 at 15:29
  • Yes i adapted your code and seems working! thank you very much for your time :) – r4id4 Feb 24 '14 at 15:33
  • just one last question! in the void run() it looks like i have to set `frame.add(new myConstructor())` for any window i'll create right? – r4id4 Feb 24 '14 at 15:35
  • No, your `createAndShowGUI` already insitializes everything. You can leave everything the same. – Paul Samsotha Feb 24 '14 at 15:36