English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

class MyButtonListener implements ItemListener{

RadioButtonTestFrame theFrame;
MyButtonListener(RadioButtonTestFrame aFrame){
theFrame=aFrame;
}
public void itemStateChanged(ItemEvent e){
JRadioButton theButton=(JRadioButton)e.getItem();

if(theButton.getText().equals(\"Color.RED\")){
theFrame.theTextArea.setForeground(Color.RED);
}else if(theButton.getText().equals(\"Color.GREEN\")){
theFrame.theTextArea.setForeground(Color.GREEN);
}else if(theButton.getText().equals(\"Color.BLUE\")){
theFrame.theTextArea.setForeground(Color.BLUE);
}
JCheckBox theBox=(JCheckBox)e.getItem();
String fontName=theFrame.theTextArea.getFont().getName();
int fontSize=theFrame.theTextArea.getFont().getSize();
int fontStyle=Font.PLAIN;
if(theFrame.theBox1.isSelected()){
if(theFrame.theBox2.isSelected()){
fontStyle=Font.BOLD+Font.ITALIC;
}else{
fontStyle=Font.BOLD;
}
}else{
if(theFrame.theBox2.isSelected()){
fontStyle=Font.ITALIC;
}else{
fontStyle=Font.PLAIN;
}
}
theFrame.theTextArea.setFont(new Font(fontName, fontStyle, fontSize));
}
}

====
一個用來改變字型,一個是顏色~但兩個好像衝到,只能一個working?why?

2006-06-20 15:53:38 · 1 個解答 · 發問者 暗黑中的紅月 2 in 電腦與網際網路 程式設計

1 個解答

 在 itemStateChanged() 方法中,e.getItem() 傳回的物件被轉換成 JRadioButton 及 JCheckBox,因此一定會在某一次的轉換中產生例外事件。解決方法是用 instanceof 來判別該物件的類別為何,再轉換之。以下是我做了變更的程式碼,供你參考(藍字為變更部分)。 public void itemStateChanged(ItemEvent e){  Object obj = e.getItem();  if (obj instanceof JRadioButton) {   JRadioButton theButton=(JRadioButton)obj;   if(theButton.getText().equals("Color.RED")){    theFrame.theTextArea.setForeground(Color.RED);   }else if(theButton.getText().equals("Color.GREEN")){    theFrame.theTextArea.setForeground(Color.GREEN);   }else if(theButton.getText().equals("Color.BLUE")){    theFrame.theTextArea.setForeground(Color.BLUE);   }  } else if (obj instanceof JCheckBox) {   JCheckBox theBox=(JCheckBox)obj;   String fontName=theFrame.theTextArea.getFont().getName();   int fontSize=theFrame.theTextArea.getFont().getSize();   int fontStyle=Font.PLAIN;   if(theFrame.theBox1.isSelected()){    if(theFrame.theBox2.isSelected()){     fontStyle=Font.BOLD+Font.ITALIC;    }else{     fontStyle=Font.BOLD;    }   }else{    if(theFrame.theBox2.isSelected()){     fontStyle=Font.ITALIC;    }else{     fontStyle=Font.PLAIN;    }   }   theFrame.theTextArea.setFont(new Font(fontName, fontStyle, fontSize));  } }

2006-06-21 19:23:19 · answer #1 · answered by ? 7 · 0 0

fedest.com, questions and answers