设置JTextFrame的高度 [英] Setting the height of a JTextFrame

查看:66
本文介绍了设置JTextFrame的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的类创建一个表单(Jpanel),其任务是从用户那里获取多个String并对其进行处理.它可以正常工作,但令我感到困惑的是,JTextField s(允许修改一个文本行的组件)的高度会自动调整,并且可能变得过大.

The following class creates a form (Jpanel) tasked with acquiring multiples Strings from the user and do something with them. It it functionally working, but it bugs me that the height of the JTextFields (a component that allows for the modification of one line of text) is automatically adjusted and can became extravagantly big.

我已经尝试过方法setBounds(),但是:

I have tried the method setBounds(), but:

  1. 我不想计算JTextField的位置或宽度,而只是计算其高度;和
  2. 它不会限制JTextField的高度!
  1. I do not want to calculate the position or width of the JTextField, just its height; and
  2. It does not limit the height of the JTextField!

有什么建议吗?

public class MultiplesStrings extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1106317992372206473L;

    /** The greater {@link JPanel}.                                                                 */
    private JPanel contentPane;

    private JPanel[] interaction;
    private JLabel[] text;
    private JTextField[] insertText;


    /** The {@link JButton} that submits the form information.                                      */
    JButton button;

    @SuppressWarnings("unused")
    private Consumer<MultiplesStrings> instructions;

    // =========================================================            
        // TODO | Constructor

    /**
     * Create the frame.
     */
    public MultiplesStrings(String title, String[] messages, 
                int x, int y, int width, int height, 
                Consumer<MultiplesStrings> instructions) {

        // ===== MAIN FRAME DEFINITION =====

        this.setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(x, y, width, height);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        setContentPane(contentPane);
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
    //  contentPane.setBackground(Colours.newColor("DDDDDD"));

        // ===== INTERACTION FRAME DEFINITION =====

        this.interaction = new JPanel[messages.length];
        this.text       = new JLabel[messages.length];
        this.insertText = new JTextField[messages.length];
        for(int i=0 ; i<messages.length ; i++)
            {
            interaction[i] = new JPanel();
            interaction[i].setLayout(new BoxLayout(interaction[i], BoxLayout.LINE_AXIS));
            interaction[i].setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
            interaction[i].add(Box.createHorizontalGlue());

            // ===== TEXT =====
            text[i] = new JLabel(messages[i]);
            text[i].setAlignmentY(RIGHT_ALIGNMENT);
        //  text.setBounds(0, imageResolution + margin, Width, buttonHeight);

            interaction[i].add(text[i]);

            // ===== INSERT TEXT FIELD =====
            insertText[i] = new JTextField();
        //  this.insertTextField.setBounds(Width + margin, imageResolution + margin, moveWidth, buttonHeight);
            insertText[i].setColumns(10);

            interaction[i].add(insertText[i]);

            this.add(interaction[i]);
            }

        // ===== SUBMIT BUTTON DEFINITION =====

        this.button = new JButton("Submit");

        // Button behavior
        MultiplesStrings support = this;
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {         }
            } );
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {     
                instructions.accept(support);       
        //      support.setVisible(false);
                }
            } );
        this.getRootPane().setDefaultButton(button);


        this.add(button);
    }

    // =========================================================            
        // TODO | Input-output manipulation

    /** Acquires all {@link String}s written by the user in the {@link JTextField}s used for {@code interactions}.  */
    public String[] acquireInputs() {
        String[] output = new String[interaction.length];
        for(int i=0 ; i<output.length ; i++)
            output[i] = insertText[i].getText();
        return output;
    }


    // =========================================================            
        // TODO | Main

    public static final int width   = 300;
    public static final int height  = 500;

    private static String[] input;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() { public void run() {
            try {
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                double screenWidth = screenSize.getWidth();
                double screenHeight = screenSize.getHeight();

                // Creates a centered form
                MultiplesStrings ms = new MultiplesStrings("Test", 
                    new String[] { "Insert first string: ", "Insert second string: ", "Insert third string: "},
                    (int) (screenWidth-width)/2,    (int) (screenHeight-height)/2, width, height, 
                    (MultiplesStrings obj) ->
                        {
                        input = obj.acquireInputs();
                        for(int i=0 ; i<input.length ; i++)
                            System.out.println("The " + i + "-th input is: " + input[i]);
                        }
                    );
                ms.setVisible(true); 

                } catch (Exception e) {         e.printStackTrace();                                }
        }
    });
}


}

推荐答案

这是因为BoxLayout使用了容器的整个空间.换句话说,它会拉伸所有组件以利用总的可用空间(因为您使用PAGE_AXIS,所以它指的是可用高度).

This is because BoxLayout uses the whole space of the container. With other words, it stretches all components to take the advantage of the total available space (since you use PAGE_AXIS, it refers to available height).

解决方案之一是使用BorderLayout作为外部容器,并将此BoxLayout -ed面板添加到内部,且具有BorderLayout.PAGE_START约束. PAGE_START约束指的是嘿,BoxLayout,没有可用空间供您使用".看一下这个例子:

One of the solutions is to use a BorderLayout as an outside container and add this BoxLayout-ed panel inside at, with BorderLayout.PAGE_START constraints. PAGE_START constraints refers as "Hey you BoxLayout, there is no available space for you". Take a look at this example:

public class BoxLayoutSample extends JFrame {
    public BoxLayoutSample() {
        super("");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = getContentPane();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

        contentPane.add(new JTextField(15));
        contentPane.add(new JTextField(15));

        setLocationByPlatform(true);
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
    }

}

它给我们:

这就是你现在拥有的.

但是,如果您使用的是外部BorderLayout版面板:

But if you use an outside BorderLayout-ed panel:

public class BoxLayoutSample extends JFrame {
    public BoxLayoutSample() {
        super("");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = getContentPane(); //This is the outer panel
        contentPane.setLayout(new BorderLayout());

        JPanel boxLayoutPanel = new JPanel(); //This is the nested panel
        boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));

        //Components to nested panel
        boxLayoutPanel.add(new JTextField(15));
        boxLayoutPanel.add(new JTextField(15));


        //PAGE_START to wrap it on the top
        contentPane.add(boxLayoutPanel, BorderLayout.PAGE_START);

        setLocationByPlatform(true);
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
    }
}

您得到:

此外,如果组件中包含布局,则调用setBounds方法将被忽略.为了看到setBounds效果,您必须container.setLayout(null),因为布局负责组件的边界.但是,不建议这样做. 逐步使用布局管理器.让他们为您服务.

Also, calling setBounds method to a component will be ignored if it contains a layout. In order to see setBounds effect you must container.setLayout(null) since the layout is responsible for the component's bounds. However, THIS IS NOT RECOMMENDED. INSTEAD USE LAYOUT MANAGERS. Let them work for you.

这篇关于设置JTextFrame的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆