开发者

Applet panels, one fixed size, and dynamic JTextField

开发者 https://www.devze.com 2022-12-31 06:00 出处:网络
I need an applet which contains one panel. The panel needs to be 550x400 pixels, the JTextField needs to be under the panel dynamic size. I want it to be like this:

I need an applet which contains one panel. The panel needs to be 550x400 pixels, the JTextField needs to be under the panel dynamic size. I want it to be like this: [topPanel] [textPanel]

However I am try开发者_运维技巧ing this, and it seems like the panel is filling all the space. The code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Client extends JApplet
{

@Override
public void init()
{
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable()
            {

            public void run()
            {
                initComponents();
            }
            });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void initComponents()
{
    JPanel topPanel = new javax.swing.JPanel();

    topPanel.setBackground(Color.red);

    topPanel.setSize(550, 400);
    topPanel.setPreferredSize(new Dimension(550, 400));
    topPanel.setMinimumSize(new Dimension(550, 400));
    topPanel.setMaximumSize(new Dimension(550, 400));

    JTextField myTextBox = new JTextField(255);

    getContentPane().add(topPanel, java.awt.BorderLayout.NORTH);
    getContentPane().add(myTextBox, java.awt.BorderLayout.SOUTH);
}
// TODO overwrite start(), stop() and destroy() methods
}

Thanks!


The components seemed to be in the correct positions when I tested the above code. The only thing I noticed was that the initial view-port size was smaller than 550x400. This caused some artifacts in displaying the JTextField since the size of the JPanel is invariably 550x400.


The JPanel seems correct (using setPreferredSize, adding to NORTH) assuming the your applet is 550 wide and at least 400 high. I might try moving the text field to CENTER instead of SOUTH because of how BorderLayout stretches its components. According to the Javadocs:

The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.

So putting the text field into the center should give it the vertical stretch you are looking for to enable it to take up the rest of the applet's available space.

0

精彩评论

暂无评论...
验证码 换一张
取 消