0

L&Fの数を切り替える小さなプログラムを作成します。リストからL&Fを選択するだけで、ボタンの外観が異なります。

しかし、2回目のチャンスでは変わらない

そして私はJavaの初心者です:)

これは私のコード

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

int selectedIndices[] = jList1.getSelectedIndices();
try {
for (int j = 0; j < selectedIndices.length; j++){
if(j == 0){
  UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
   SwingUtilities.updateComponentTreeUI(this);
             this.pack();
}
if(j == 1){
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
 SwingUtilities.updateComponentTreeUI(this);
              this.pack();
 }
 if(j == 2){
 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
 SwingUtilities.updateComponentTreeUI(this);
             // this.pack();
}
if(j == 3){
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
  SwingUtilities.updateComponentTreeUI(this);
             this.pack();
}
}
}
catch (Exception e) {
               } 
     }
4

3 に答える 3

3

アイテムが1つだけ選択されている場合(その場合だと思います)、コードは常にMotifLookAndFeelを選択します。

  • selectedIndices.lengthは1です
  • したがって、forループのjは、値として0のみを取ります。
  • MotifLookAndFeelが選択されています。

代わりに、おそらく次のようなことをしたいと思うでしょう。

switch (jList1.getSelectedIndex()) {
    case 0:
       //select 1st L&F
       return;
    case 1:
       //select 2nd L&F
       return;
    case 2:
       //select 3rd L&F
       return;
}
于 2012-04-26T18:17:38.470 に答える
1

このコードにはいくつかの問題があります。

  1. 配列をループしfor (int j = 0; j < selectedIndices.length; j++)ますが、配列内のエントリは使用しませんselectedIndices[j]。代わりに を使用しますj
  2. j==0これで、いつ使用するかがハードコーディングされましたMotifLookAndFeel。通常、selectedIndex を使用してリストからデータを取得し (= ルック アンド フィールの識別子)、その識別子を使用してルック アンド フィールを変更します。
  3. コードを単に で囲むのは非常に悪い習慣try{} catch( Exception e ){}です。たとえば、すべてExceptionの s、チェック済み例外、実行時例外をキャッチします。さらに、例外を除いて何もしません。少なくともブロックにe.printStackTrace()呼び出しを入れcatchて、何かがうまくいかなかったことが実際にわかるようにします
  4. 私の個人的な経験では、ルック アンド フィールからの切り替えは、標準のルック アンド フィール (メタル) からシステム固有のルック アンド フィールにうまくいきます。しかし、Metal - OS 固有 - Nimbus - Metal - .... からの切り替えは、奇妙な結果につながります。

先に進むために、そのコードを(上記の問題を説明するための非コンパイル擬似コード)のように記述します

//where the list is created 
//only allow single selection since I cannot set multiple L&F at the same time      
jList1.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

//button handling
int selectedIndex = jList1.getSelectedIndex();
if ( selectedIndex == -1 ) { return; } //no selection
MyLookAndFeelIdentifier identifier = jList1.getModel().getElementAt( selectedIndex );   
try{   
  UIManager.setLookAndFeel( identifier.getLookAndFeel() ); 
} catch ( UnsupportedLookAndFeelException e ){    
   e.printStackTrace(); 
}
于 2012-04-26T18:22:45.747 に答える
0

『Java How To Program』には、同様のプログラム例があります。Link1Link2

于 2012-04-26T18:17:31.003 に答える