簡體   English   中英

JTextField-將邊框重置為系統默認值

[英]JTextField - Reset Border to System Default

我正在嘗試將JTextFieldBorder顏色設置為紅色,然后稍后將其更改回“正常”狀態。 當我使用Linux(Ubuntu的另外),初始Border從不同的Border ,你通過得到UIManager.getBorder("TextField.border"); 其中一個是SynthBorder ,另一個是FieldBorder “正確”的將是SynthBorder

SSCCE:

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main
{
  private static boolean switched;

  public static void main( final String[] args )
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
  {
    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );

    JFrame frame = new JFrame( "Test border change" );
    frame.getContentPane().setLayout( new BoxLayout( frame.getContentPane(), BoxLayout.LINE_AXIS ) );
    JTextField tf = new JTextField();
    JButton button = new JButton( "Switch" );
    button.addActionListener( action ->
    {
      if ( switched )
      {
        tf.setBorder( UIManager.getBorder( "TextField.border" ) );
        switched = !switched;
      }
      else
      {
        tf.setBorder( BorderFactory.createLineBorder( Color.RED ) );
        switched = !switched;
      }
    } );
    frame.getContentPane().add( tf );
    frame.getContentPane().add( button );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible( true );
  }
}

我已經嘗試過:

  • 使用JComponent.updateUI() (無效)
  • 使邊框無效(破壞布局)
  • 保存(不正確的方法)

有誰有更好的主意嗎?

當您更換邊框時,請嘗試使用:

Border uiBorder = BorderUIResource( BorderFactory.createLineBorder( Color.RED ) );
tf.setBorder( uiBorder );

當您將任何包裝器類與“ UIResource”一起使用時,這會告訴LAF該組件是LAF的一部分,而不是自定義實現

然后恢復邊框:

SwingUtilities.updateComponentTreeUI( tf );

希望這會偽造UI來重置LAF屬性,特別是Border。

閱讀Swing教程中有關如何設置LAF的部分, 獲取更多信息。

當然,這不如簡單地保存Border updatComponentTreeUI(...)設邊框那樣有效,因為updatComponentTreeUI(...)將更新文本字段的所有屬性(如果updatComponentTreeUI(...) )。

仍然不明白為什么您不能保存邊界。 您可以使用JComponent類的putClientProperty(...)方法保存Border,然后使用getClientProperty(...)方法將其還原。

您甚至可以通過添加PropertyChangeListener來監聽邊框的變化,從而實現自動化。 如果getClientProperty(...)返回null時生成事件,則可以保存PropertyChangeEvent的舊值。

您可以使用以下代碼在UIManager獲取默認邊框

jTextField2.setBorder(UIManager.getLookAndFeel().getDefaults().getBorder("TextField.border"));
yourJTextField.setBorder(new JTextField().getBorder());

您可以在創建要保存的組件后立即獲得邊框,然后稍后再進行設置。

Border defaultBorder = tf.getBorder();
...
tf.setBorder(defaultBorder);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM