简体   繁体   中英

How can I properly align my labels?

More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.

I've uploaded an image of the current program running :

图片

As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.

Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.

Thanks for taking the time to read this!

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField; 

public class GradePanel2 extends JPanel {

private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;

public GradePanel2() {

    // Button to add entry to list
    addEntry = new JButton("Add entry to list");
    addEntry.addActionListener(new buttonListener());

    // Button to print all entries in correct format
    calculate = new JButton("Print all user grades");
    calculate.addActionListener(new buttonListener());

    //Create Labels
    name = new JLabel("Enter student name: ");
    nameField = new JTextField(10);
    nameField.addActionListener(new buttonListener());

    grade = new JLabel("Enter students mark: ");
    gradeField = new JTextField(5);
    gradeField.addActionListener(new buttonListener());

    //Result Labels
    nameResult = new JLabel("NAME");
    gradeResult = new JLabel("GRADE");


    //Bottom segment for result
    resultField = new JTextField();
    resultField.setOpaque(false);
    resultField.setEditable(false);

    setLayout(new BorderLayout());

    //Bottom Panel
    JPanel GradePanel = new JPanel();
        GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
    GradePanel.setOpaque(false);
    GradePanel.setPreferredSize(new Dimension(0 , 100));
    GradePanel.add(resultField);
    resultField.setAlignmentX(LEFT_ALIGNMENT);
    GradePanel.add(nameResult);
    GradePanel.add(gradeResult);

    //Button Panel
    JPanel ButtonPane = new JPanel();
    ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
    addEntry.setAlignmentX(CENTER_ALIGNMENT);
    calculate.setAlignmentX(CENTER_ALIGNMENT);
    ButtonPane.add(addEntry);
    ButtonPane.add(Box.createVerticalStrut(10));
    ButtonPane.add(calculate);

    //Label Panel
    JPanel labelPane = new JPanel();
    labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
    labelPane.add(name);
    labelPane.add(Box.createRigidArea(new Dimension (5,0)));
    labelPane.add(nameField);
    labelPane.add(Box.createRigidArea(new Dimension (0,2)));
    labelPane.add(grade);
    labelPane.add(Box.createRigidArea(new Dimension (5,0)));
    labelPane.add(gradeField);

    //Add all panels to the main panel
    add(labelPane, BorderLayout.NORTH); 
    add(ButtonPane, BorderLayout.CENTER);
    add(GradePanel, BorderLayout.SOUTH);

    setBackground(Color.WHITE);
    setPreferredSize(new Dimension(400, 300));
}

public class buttonListener implements ActionListener{

    public void actionPerformed(ActionEvent event){

        String studentName;
        int studentMark;

        studentName = nameField.getText();
        String intMark = gradeField.getText();
        studentMark = Integer.parseInt(intMark);



    }
}

}

and then the driver class:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
    @Override
    public void run() {

        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GradePanel2 panel = new GradePanel2();
        frame.add(panel);

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

    }
};
    SwingUtilities.invokeLater(runnable);
}}

Take time to read this the most flexible Layout Manager that commonly used by programmer :) https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read. https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

    import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField; 

public class GradePanel2 extends JPanel {

private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;

public GradePanel2() {

    // Button to add entry to list
    addEntry = new JButton("Add entry to list");
    addEntry.addActionListener(new buttonListener());

    // Button to print all entries in correct format
    calculate = new JButton("Print all user grades");
    calculate.addActionListener(new buttonListener());

    //Create Labels
    name = new JLabel("Enter student name: ");
    nameField = new JTextField(10);
    nameField.addActionListener(new buttonListener());

    grade = new JLabel("Enter students mark: ");
    gradeField = new JTextField(5);
    gradeField.addActionListener(new buttonListener());


    //Bottom segment for result
    resultField = new JTextField();
    resultField.setOpaque(false);
    resultField.setEditable(false);

    setLayout(new BorderLayout());
    GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
    GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints


    //Button Panel
    JPanel ButtonPane = new JPanel();
    ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
    addEntry.setAlignmentX(CENTER_ALIGNMENT);
    calculate.setAlignmentX(CENTER_ALIGNMENT);
    ButtonPane.add(addEntry);
    ButtonPane.add(Box.createVerticalStrut(10));
    ButtonPane.add(calculate);

    //Label Panel
    JPanel labelPane = new JPanel();
    labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
    labelPane.add(name);
    labelPane.add(Box.createRigidArea(new Dimension (5,0)));
    labelPane.add(nameField);
    labelPane.add(Box.createRigidArea(new Dimension (0,2)));
    labelPane.add(grade);
    labelPane.add(Box.createRigidArea(new Dimension (5,0)));
    labelPane.add(gradeField);

    myBottomPanel mybottompanel = new myBottomPanel();//Object

    //Add all panels to the main panel
    add(labelPane, BorderLayout.NORTH); 
    add(ButtonPane, BorderLayout.CENTER);
    add(mybottompanel, BorderLayout.SOUTH);

    setBackground(Color.WHITE);
    setPreferredSize(new Dimension(400, 300));
}

public class myBottomPanel extends JPanel{
    public myBottomPanel()
    {
        this.setLayout(new GridBagLayout());

        //Result Labels
         nameResult = new JLabel("NAME");
         gradeResult = new JLabel("GRADE");

         //Constraints
        GridBagConstraints nameResultConstraints = new GridBagConstraints();
        GridBagConstraints gradeResultConstraints = new GridBagConstraints();

        //Bottom Panel
        setBorder(BorderFactory.createTitledBorder("Students/Results"));
        setOpaque(false);
        setPreferredSize(new Dimension(0 , 100));

        nameResultConstraints.anchor = GridBagConstraints.LINE_START;
        nameResultConstraints.weightx = 0.5;
        nameResultConstraints.weighty = 0.5;

        add(nameResult,nameResultConstraints);
        add(gradeResult);

    }
}
public class buttonListener implements ActionListener{

    public void actionPerformed(ActionEvent event){

        String studentName;
        int studentMark;

        studentName = nameField.getText();
        String intMark = gradeField.getText();
        studentMark = Integer.parseInt(intMark);



    }
}

}

and here is your Frame.

    import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
    @Override
    public void run() {

        JFrame frame = new JFrame("Grade Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GradePanel2 panel = new GradePanel2();
        frame.add(panel);

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

    }
};
    SwingUtilities.invokeLater(runnable);
}}

OUTPUT

在此处输入图片说明

Hope this helps. :)

If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.

Maybe you can use a GridBagLayout . You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.

However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables .

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