在java中的外观和感觉
我写了一个小程序,将切换数量L & F 只需从列表中选择L & F,按钮将看起来不同。当第二次机会在java中的外观和感觉
,我初学者用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循环,将仅取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;
}
非常感谢 – imalak 2012-04-26 19:47:24
没有与此代码的几个问题。
- 您遍历数组
for (int j = 0; j < selectedIndices.length; j++)
但你的阵列selectedIndices[j]
中从来不使用的条目。相反,您只需使用j
。 - 现在你已经硬编码,当
j==0
你将使用MotifLookAndFeel
。通常,您可以使用selectedIndex从列表中检索数据(=外观的标识符),然后使用该标识符来更改外观 - 将代码与
try{} catch(Exception e){}
环绕在一起是非常糟糕的做法。例如,你捕获所有的Exception
,检查异常和运行时异常。此外,您不会对异常做任何事情。至少在catch
区块中拨打e.printStackTrace()
电话,以便您确实知道发生了问题 - 以我个人的体验,从外观转换到标准外观(金属)转换为系统特定外观和感觉。但是从金属 - 特定操作系统 - 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();
}
*“特定于操作系统 - Nimbus - Metal - ....导致出现奇怪的结果。”* Nimbus因引入奇怪的GUI工件而臭名昭着。 :( – 2012-04-26 19:58:08
@AndrewThompson我也遇到过与其他L&Fs(Motif,Kunstoff,...)。从金属切换到其中之一并返回是没有问题的,但是从非金属切换到另一个非金属几乎总是会导致我有印象JDK1.6改进了这一点(1.4和1.5只是一场灾难),但它还远未完善 – Robin 2012-04-26 20:44:39
你曾经有超过1个选择的指标吗?使用j只是一个索引变量似乎不正确... – ControlAltDel 2012-04-26 18:16:02