在JTextField周围的TitledBorder

时间:2013-03-15 02:21:15

标签: java swing

在java中,当我在JTextField周围使用TitledBorder时,部分JTextField会在所有方向上溢出TitledBorder。有办法防止这种情况吗?

2 个答案:

答案 0 :(得分:1)

如果用TitledBorder替换文本字段的边框,则会丢失字段的自然边框。解决方案是创建CompoundBorder,将TitledBorder与字段边框结合起来:

JTextField field = new JTextField(10);
field.setBorder(new CompoundBorder(BorderFactory.createTitledBorder("Title"), field.getBorder()));

然而,TitledBorder仍然继承了文本字段的背景颜色。

另一个解决方案是将文本字段嵌入JPanel并将TitledBorder放在面板上:

JTextField field = new JTextField(10);

JPanel borderPanel = new JPanel();
borderPanel.setBorder(BorderFactory.createTitledBorder("Title"));
borderPanel.add(field);

答案 1 :(得分:0)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AA
{
    public static void main(String[] args)
    {
        FrameCreator Frame= new FrameCreator();
        Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Frame.setVisible(true);
    }
}

class FrameCreator extends JFrame
{
    public FrameCreator()
    {
        int height=100;
        int width=300;
        setSize(width,height);
        setLocation(0,0);

        setTitle("TextField example");

        showPanel=new JPanel();
        textFieldPanel=new JPanel();

        label=new JLabel("Sentence");
        label.setFont(new Font("Serif",Font.PLAIN,12));

        showPanel.add(label);
        add(showPanel, BorderLayout.CENTER);


        textfield=new JTextField("Sentence", 20);
        textfield.setBorder(BorderFactory.createTitledBorder("Name"));
        textfield.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent evento1)
                {

                    String sentence=textfield.getText();


                    label.setText(sentence);
                }
            });


        textFieldPanel.add(textfield);
        add(textFieldPanel, BorderLayout.SOUTH);
    }

    JLabel label;
    JPanel showPanel, textFieldPanel;
    String sentence;
    JTextField textfield;
}

我使用过textfield.setBorder(BorderFactory.createTitledBorder(“Name”));