繁体   English   中英

Java列表中的外观

[英]Look and Feel in List in java

我编写了一个可以在L&F数量之间切换的小程序,只需从列表中选择L&F,按钮的外观就会有所不同。

但第二次机会不变

我是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) {
               } 
     }

如果只选择一项(我想是这样),那么您的代码将始终选择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;
}

此代码存在一些问题。

  1. for (int j = 0; j < selectedIndices.length; j++)遍历一个数组for (int j = 0; j < selectedIndices.length; j++)但是从不使用selectedIndices[j]数组中的条目。 相反,您只使用j
  2. 现在您已经硬编码,当j==0 ,将使用MotifLookAndFeel 通常,您将使用selectedIndex从列表中检索数据(=外观标识符),并使用该标识符更改外观
  3. 仅用try{} catch( Exception e ){}包围代码是非常不好的做法。 例如,您捕获所有Exception ,已检查的异常和运行时异常。 此外,除此以外,您什么也不做。 至少在catch块中放置一个e.printStackTrace()调用,以便您实际上知道出了点问题
  4. 以我的个人经验,从外观切换从标准外观(金属)过渡到特定于系统的外观。 但是从Metal-特定于操作系统-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(); 
}

《 Java How To Program》一书有一个类似的程序示例。 链接1链路2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM