在java中,当我在JTextField周围使用TitledBorder时,部分JTextField会在所有方向上溢出TitledBorder。有办法防止这种情况吗?
答案 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”));