在 java 中,当我在 JTextField 周围使用 TitledBorder 时,JTextField 的一部分会在各个方向上溢出 TitledBorder。有没有办法防止这种情况?
问问题
2372 次
2 回答
1
如果用 a 替换文本字段的TitledBorder
边框,则会丢失该字段的自然边框。解决方案是创建一个与字段边界CompoundBorder
相结合的:TitledBorder
JTextField field = new JTextField(10);
field.setBorder(new CompoundBorder(BorderFactory.createTitledBorder("Title"), field.getBorder()));
但是 TitledBorder 仍然继承文本字段的背景颜色。
另一种解决方案是将文本字段嵌入 aJPanel
并将其TitledBorder
放在面板上:
JTextField field = new JTextField(10);
JPanel borderPanel = new JPanel();
borderPanel.setBorder(BorderFactory.createTitledBorder("Title"));
borderPanel.add(field);
于 2013-03-15T09:03:05.640 回答
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"));
于 2013-03-15T16:49:40.997 回答