Java设置JTextField位置

时间:2015-02-13 17:51:43

标签: java swing user-interface jframe jtextfield

如何定位JTextField?我搜索了很多例子,但不幸的是没有人为我工作。有人能帮我吗?我想用绝对坐标来定位它。

代码:

public static class TextDemo extends JPanel implements ActionListener {
  protected JTextField textField;
  static public String text;

  public TextDemo() {
    super(new GridBagLayout());

    textField = new JTextField(20);
    textField.addActionListener(this);

    textField.setBounds(10,10,200,40);
    //textField.setSize(500,500);

    //Add Components to this panel.
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;

    c.fill = GridBagConstraints.HORIZONTAL;
    add(textField, c);

    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
  }

  public void actionPerformed(ActionEvent evt) {
    text = textField.getText();
  }

  public static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TextDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add contents to the window.
    frame.add(new TextDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
}

1 个答案:

答案 0 :(得分:0)

我不确定你想要达到的目的是什么,但如果你的意愿是将文本字段定位在10,10位置,你可以这样做:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TextDemo extends JPanel implements ActionListener {
    private JTextField textField;
    private String text;

    public TextDemo() {
        super(new GridBagLayout());

        textField = new JTextField(20); // Here 20 gives a hint on the width of the textfield
        textField.addActionListener(this);

        // Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.insets = new Insets(10, 10, 10, 10);
        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        text = textField.getText();
    }

    public static void main(String[] args) {
        // Create and set up the window.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("TextDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                // Add contents to the window.
                frame.add(new TextDemo());

                // Display the window.
                frame.pack();
                frame.setMinimumSize(frame.getPreferredSize());
                frame.setVisible(true);

            }
        });
    }
}