简体   繁体   中英

Java - set a size to JDialog

I have a strange problem, i did two class (They are very similar), but in the first Class the setPreferredSize method, works in the other not; so i have to use (in this class) setSize() method. And this is really strange. I post my code:

In this class it works well

package StudentNotes;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Timer;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;

import StudentNotes.TextPrompt.Show;

import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class CreateCourse extends JDialog {
    private JTextField tFieldCourseName;


    /**
     * Create the dialog.
     */
    public CreateCourse(JDialog mainFrame, final StudApp studAppObj) {
        super(mainFrame, ModalityType.APPLICATION_MODAL);
        setPreferredSize(new Dimension(330, 200)); //it works
        setTitle("Create a course");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);

        tFieldCourseName = new JTextField();
        tFieldCourseName.setFont(new Font("Tahoma", Font.BOLD, 14));
        tFieldCourseName.setColumns(10);
        TextPrompt tp = new TextPrompt("Course name", tFieldCourseName);
        tp.changeStyle(Font.ITALIC);
        tp.setShow(Show.ALWAYS);
        tp.setForeground(Color.GRAY);

        final JLabel lblAllertcourse = new JLabel("");
        lblAllertcourse.setHorizontalAlignment(SwingConstants.CENTER);

        JButton btnAddCourse = new JButton("Add course");
        btnAddCourse.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                javax.swing.Timer t = new javax.swing.Timer(2000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        lblAllertcourse.setText("");
                    }
                });

                String nameCourse = tFieldCourseName.getText();
                ArrayList<Corso> courses = studAppObj.getCorsi();

                if (nameCourse.equals("")) {
                    lblAllertcourse.setText("Insert a valid name course!");
                    t.setRepeats(false);
                    t.start();
                    return;
                }   

                for (Corso currentCourse : courses) {
                    if (currentCourse.name.toUpperCase().equals(nameCourse.toUpperCase())) {
                        lblAllertcourse.setText("This course already exist!");
                        t.setRepeats(false);
                        t.start();
                        return;
                    }
                }
                studAppObj.setCorsi(new Corso(), nameCourse);
                lblAllertcourse.setText("Course added successfully");
                t.setRepeats(false);
                t.start();
            }
        });

        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(113)
                            .addComponent(btnAddCourse))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(103)
                            .addComponent(tFieldCourseName, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(lblAllertcourse, GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)))
                    .addContainerGap())
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(46)
                    .addComponent(tFieldCourseName, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(btnAddCourse)
                    .addPreferredGap(ComponentPlacement.UNRELATED)
                    .addComponent(lblAllertcourse)
                    .addContainerGap(44, Short.MAX_VALUE))
        );
        getContentPane().setLayout(groupLayout);
        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

in this other class setPreferredSize does not work, the JDialog doesnt have a size so it reamins small ( i can just see the title of the Dialog and not more).

package StudentNotes;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;

public class EditCourse extends JDialog {

    /**
     * Create the dialog.
     */
    public EditCourse(JDialog mainFrame, final StudApp studAppObj) {
        super(mainFrame, ModalityType.APPLICATION_MODAL);

        //I have to use setSize
        // if i use setPreferredSize does not work
        setSize(new Dimension(330, 200));
        setTitle("Edit course");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);

        ArrayList<Corso> listCourses = studAppObj.getCorsi();
        listCourses.toArray();

        String[] listData = { "one", "two", "three", "four",
                              "five", "six", "seven" };
        JList list = new JList(listData);
        list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {

                if (e.getValueIsAdjusting() == true) {
                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    int minIndex = lsm.getMinSelectionIndex();
                    int maxIndex = lsm.getMaxSelectionIndex();
                    for (int i=minIndex; i<=maxIndex; i++) {
                        if (lsm.isSelectedIndex(i)) {
                            System.out.println("hai selezionato l'indice nr. "+i);
                        }
                    }
                }
            }
        });
        JScrollPane scrollPane = new JScrollPane(list);
        scrollPane.setSize(new Dimension(118, 40));

        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(108)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(108, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGap(21)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(87, Short.MAX_VALUE))
        );
        getContentPane().setLayout(groupLayout);

        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

In the second class there's no call to pack() method and that's why the dialog remains "small":

public void pack()

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.

You should also take a look to this topic: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

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