如何在java中设置JTextField边框大小

时间:2014-02-17 05:49:14

标签: java swing layout border jtextfield

我想设置边框高度,JTextField的宽度,并希望将它放在java中JFrame的中心。 我试过这些想法,但这些想法不起作用。 的setSize(),SetPrefferedSize(),SetMaximumSize();

需要帮助。提前谢谢。

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class P{
    public static void main(String [] args){
        JFrame frame = new JFrame();
        JTextField field = new JTextField();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(BorderLayout.NORTH,field);
        frame.setSize(350,300);
        frame.setVisible(true);

    }
}

1 个答案:

答案 0 :(得分:2)

您可以尝试使用LineBorder上的JTextField并使用GridBagLayout将其置于容器中

例如......

TextField

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class BorderText {

    public static void main(String[] args) {
        new BorderText();
    }

    public BorderText() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(10);
                field.setBorder(new LineBorder(Color.RED, 10));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

请查看How to Use BordersA Visual Guide to Layout Managers了解详情