views:

237

answers:

2

Hi, 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 trying 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!

A: 

Hey,

The components seem 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 sicnce the size of the JPanel is invariable 550x400.

-Tj

TjeerdB
A: 

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.

Jeff