我制作了一個框架并在其中放置了一個按鈕和一個文本欄位。我正在使用 setmargin 方法在插入符號和文本欄位的邊框之間設定邊距,并且在我向其添加邊框之前作業得非常好。添加邊框后, setmargin 方法不起作用。
能否請您幫我理解問題的根源并找到同時具有邊框和一定邊距的替代方法?
非常感謝你。
公共類 main 擴展了 JFrame {
public static void main(String[]args){
JTextField textfield0;
JButton button0;
Border border7=BorderFactory.createDashedBorder(new Color(0xA524FF), 2, 5, 4, true);
Border border8=BorderFactory.createCompoundBorder();
Border border01=BorderFactory.createLineBorder(Color.RED);
Border border02=BorderFactory.createLineBorder(Color.YELLOW);
Border border9=BorderFactory.createCompoundBorder(border01, border02);
textfield0=new JTextField();
textfield0.setPreferredSize(new Dimension(300,30));
textfield0.setFont(new Font("Consolas",Font.BOLD,15));
textfield0.setCaretColor(Color.RED);
textfield0.setBackground(Color.CYAN);
textfield0.setForeground(Color.MAGENTA);
textfield0.setText("name");
//textfield0.setBorder(border9);
textfield0.setSelectedTextColor(Color.YELLOW);
textfield0.setMargin(new Insets(0,7,0,5));
textfield0.setCaretPosition(0);
textfield0.setSelectionColor(Color.PINK);
button0=new JButton();
button0.setText("submit");
button0.setPreferredSize(new Dimension(100,30));
button0.setFocusable(false);
button0.setBackground(textfield0.getBackground());
button0.setFont(textfield0.getFont());
button0.setBorder(textfield0.getBorder());
JFrame frame00=new JFrame();
frame00.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame00.setLayout(new FlowLayout());
frame00.add(button0);
frame00.add(textfield0);
frame00.pack();
frame00.setVisible(true);
}
}
uj5u.com熱心網友回復:
如果您閱讀 Border 的 javadoc,它會指出:“使用 EmptyBorder 創建一個普通邊框(此機制取代了它的前身 setInsets)”
因此,您可以將 CompoundBorder 與 PlainBorder 和您正在設定的那個一起使用,或者覆寫現有 Border 上的 getBorderInsets(Component c)
uj5u.com熱心網友回復:
我們可以在 JavaDoc 中找到答案,這需要一些額外的步驟:
設定文本組件的邊框與其文本之間的邊距空間。文本組件的默認 Border 物件將使用此值來創建適當的邊距。但是,如果在文本組件上設定了非默認邊框,則 Border 物件有責任創建適當的邊距空間(否則該屬性將被有效地忽略)。
來源:https : //docs.oracle.com/javase/8/docs/api/javax/swing/text/JTextComponent.html#setMargin-java.awt.Insets-
并且要執行上述操作,我們可以執行以下兩種操作之一,我們可以使用如下所示的復合邊框:Java Swing - 使用 Line Border 設定 TextArea 上的邊距,或者我們可以采取以下步驟:
覆寫兩者
AbstractBorder.getBorderInsets(Component c)并AbstractBorder.getBorderInsets(Component c, Insets insets)提供正確的插圖
來源:https : //docs.oracle.com/javase/tutorial/uiswing/components/border.html#custom
我強烈建議通讀以上鏈接以更好地了解邊界以及如何使用它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386767.html
上一篇:缺少Java中泛型類的型別引數?
