简体   繁体   中英

How do I line up my JLabel with the row of JLabels below it

I am attempting to line up my JLabel that reads "Power Information" with the first column of Jlabels and have it so that the columns start from the left hand side of the window and end at the right hand side of the window.

Ive tried using anchors to the first column of Jlabels and then use anchors to move the text fields as well, but the while I can move the Jlabel columns the text field columns wont move an inch.

Can someone please help me figure this out?

edit: I am attempting to create

在此输入图像描述

     public class PowerListener implements ActionListener 
     {
      public void actionPerformed(ActionEvent event)
     {
     JFrame frame = new JFrame("Power Creation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(550,400 );

        Toolkit tools = Toolkit.getDefaultToolkit();
        Dimension dim = tools.getScreenSize();

        int x = (dim.width / 2) - (frame.getWidth() / 2);
        int y = (dim.height / 2) - (frame.getHeight() / 2);

        frame.setLocation(x, y);

        //frame.setResizable(false);

         JTextField nameBox = new JTextField(6);
         JTextField levelBox = new JTextField(6);
         JTextField timingBox = new JTextField(6);

         JTextField skillBox = new JTextField(6);
         JTextField defenseBox = new JTextField(6);
         JTextField targetBox = new JTextField(6);

         JTextField RNGBox = new JTextField(6);
         JTextField encrochBox = new JTextField(6);
         JTextField restrictionBox = new JTextField(6);

         JTextField notesBox = new JTextField(4);

        JPanel panel1 = new JPanel(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        c.insets = new Insets(5,5,5,5);

        //------------------------------------------------------------
        // Power Infromation
        //------------------------------------------------------------
        JLabel main = new JLabel("Power Information");
        main.setFont(new Font("Verdana", Font.BOLD, 12));
        c.gridx = 0;
        c.gridy = 0;
        //c.insets = new Insets(15,15,15,15)l;
        c.anchor = GridBagConstraints.CENTER;

        panel1.add(main,c);

        //c.insets = new Insets(5,5,5,5);

        c.anchor = GridBagConstraints.LINE_END;
        c.gridx = 0;
        c.gridy = 6;
        JLabel lname = new JLabel("Name:");
        panel1.add(lname,c);

        c.anchor = GridBagConstraints.BASELINE_LEADING;
        c.gridx = 1;
        c.gridy = 6;
        panel1.add(nameBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 2;
        c.gridy = 6;
        JLabel lLevel = new JLabel("Level:");
        panel1.add(lLevel,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 3;
        c.gridy = 6;
        panel1.add(levelBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 4;
        c.gridy = 6;
        JLabel lTiming = new JLabel("Timing:");
        panel1.add(lTiming,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 5;
        c.gridy = 6;
        panel1.add(timingBox,c);

        c.anchor = GridBagConstraints.LINE_END;
        c.gridx = 0;
        c.gridy = 7;
        JLabel lSkill = new JLabel("Skill:");
        panel1.add(lSkill,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 1;
        c.gridy = 7;
        panel1.add(skillBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 2;
        c.gridy = 7;
        JLabel lDefense = new JLabel("Defense:");
        panel1.add(lDefense,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 3;
        c.gridy = 7;
        panel1.add(defenseBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 4;
        c.gridy = 7;
        JLabel lTarget = new JLabel("Target:");
        panel1.add(lTarget,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 5;
        c.gridy = 7;
        panel1.add(targetBox,c);

        c.anchor = GridBagConstraints.LINE_END;
        c.gridx = 0;
        c.gridy = 8;
        JLabel lRNG = new JLabel("RNG:");
        panel1.add(lRNG,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 1;
        c.gridy = 8;
        panel1.add(RNGBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 2;
        c.gridy = 8;
        JLabel lencroach= new JLabel("Encroach:");
        panel1.add(lencroach,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 3;
        c.gridy = 8;
        panel1.add(encrochBox,c);

        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 4;
        c.gridy = 8;
        JLabel lRestriction = new JLabel("Restriction:"+ " ");
        panel1.add(lRestriction,c);

        c.anchor = GridBagConstraints.CENTER;
        c.gridx = 5;
        c.gridy = 8;
        panel1.add(restrictionBox,c);

        frame.add(panel1);
        frame.setVisible(true);
 }
  • Again, I'd display the GUI as a JDialog, not as a JFrame since it looks to be a dependent child window and not the main GUI application. If you display it as a modal dialog, you'll know exactly when the user is done using it, making extraction of information from it easy.
  • You look to be ignoring the weightx and weighty properties of your GridBagConstraints.
  • You're far better off calling pack() on your GUI after adding components, and not trying to set a component's or GUI's size.

For example:

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class PowerDialogPanel extends JPanel {
    private static final int I_GAP = 4;
    public static final String[][] LABEL_TEXTS = {
        {"Name", "Level", "Timing"},
        {"Skill", "Defense", "Target"},
        {"RNG", "Encroach", "Restriction"}
    };
    private static final int TF_COLS = 10;
    private static final String TITLE_TEXT = "Power Information";
    private Map<String, JTextField> labelFieldMap = new HashMap<>();

    public PowerDialogPanel() {
        JPanel centerPanel = new JPanel(new GridBagLayout());
        for (int row = 0; row < LABEL_TEXTS.length; row++) {
            for (int col = 0; col < LABEL_TEXTS[row].length; col++) {
                String text = LABEL_TEXTS[row][col];
                JLabel label = new JLabel(text + ":");
                JTextField textField = new JTextField(TF_COLS);
                labelFieldMap.put(text, textField);

                int x = 2 * col;
                centerPanel.add(label, createGbc(x, row));
                centerPanel.add(textField, createGbc(x + 1, row));
            }
        }

        JButton submitButton = new JButton(new AbstractAction("Submit") {

            @Override
            public void actionPerformed(ActionEvent e) {
                Window win = SwingUtilities.getWindowAncestor(PowerDialogPanel.this);
                win.dispose();
            }
        });

        setLayout(new BorderLayout(I_GAP, I_GAP));
        add(new JLabel(TITLE_TEXT), BorderLayout.PAGE_START);
        add(centerPanel, BorderLayout.CENTER);
        add(submitButton, BorderLayout.PAGE_END);
    }

    public String getText(String labelText) {
        return labelFieldMap.get(labelText).getText();
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 0.0;
        gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
        gbc.anchor = x % 2 == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
        return gbc;
    }

    private static void createAndShowGui() {
        final PowerDialogPanel powerDialogPanel = new PowerDialogPanel();

        final JFrame frame = new JFrame("Power Frame");
        final JDialog dialog = new JDialog(frame, "Power Dialog", ModalityType.APPLICATION_MODAL);
        dialog.add(powerDialogPanel);
        dialog.pack();
        dialog.setLocationRelativeTo(null);

        JPanel framePanel = new JPanel();
        framePanel.add(new JButton(new AbstractAction("Show Power Dialog") {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                dialog.setVisible(true);
                for (String[] strings : LABEL_TEXTS) {
                    for (String labelText : strings) {
                        System.out.printf("%12s: %s%n", labelText, powerDialogPanel.getText(labelText));
                    }
                }
            }
        }));
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(framePanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM