How set text field location in Java GUI?
How set text field location in Java GUI?
I tried this:
public Apletas()
{
inputLine.set开发者_StackOverflowLocation(null);
inputLine.setLocation(80, 80);
add(inputLine);
}
But not working.
First, set the layout of your applet to null
:
...
public void init()
{
setLayout(null);
}
...
Ignore setLocation()
/setBounds()
& most especially setLayout(null)
. Abandon all hope (& the last remnants of sanity), ye' who enter there.
Set locations of components using layout managers.
For sizing of components, it is usually sufficient to provide the appropriate arguments in the constructor (e.g. new JTextArea(rows, columns)
), or in some cases, using layout constraints (e.g BorderLayout.CENTER
).
For spacing between components, look into both the javax.swing.border
package and arguments to the constructor of layout managers, or in some cases, layout constraints (e.g GridBagLayout
& GridBagConstraints
).
Example:
//<applet code='Apletas' width='600' height='400'></applet>
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Apletas extends JApplet {
private JTextField inputLine;
public Apletas()
{
inputLine = new JTextField(20);
JPanel mainGui = new JPanel(new BorderLayout(20,20));
mainGui.setBorder(new EmptyBorder(80,80,80,80));
mainGui.add(inputLine, BorderLayout.NORTH);
mainGui.add(new JScrollPane(new JTextArea(20,10)), BorderLayout.CENTER);
JTree tree = new JTree();
tree.expandRow(2);
mainGui.add(new JScrollPane(tree), BorderLayout.WEST);
setContentPane(mainGui);
validate();
}
}
To compile & run
prompt> javac Apletas.java
prompt> appletviewer Apletas.java
See also
Laying Out Components Within a Container & How to Use Borders in the Java Tutorial.
I'm not sure why you would .setLocation(null)
on a text field and then set it again.
Is inputLine declared elsewhere (in which case post the full code here please) or are you missing a line like
TextField inputLine = new TextField("Hello world");
You have to null the default layout as by using the code
setLayout(null);
and then can use the setBounds method to locate your swings it goes like this
JTextField jt = new JTextField();
jt.setBounds(x,y,width,height);
精彩评论