2016-10-22 48 views
-1

如標題所示,我想根據代碼中的結果顯示JFrame中的三個圖像中的一個。JFrame如何根據代碼中的結果顯示圖像?

,其確定結果的代碼是這樣的:

Equilatero,Escaleno和等腰是結果。

private void CActionPerformed(java.awt.event.ActionEvent evt) {         
 
     double la,lb,lc; 
 
     double a; 
 
     double p; 
 
     String t=null; 
 
     
 
     la=Double.parseDouble(LA.getText()); 
 
     lb=Double.parseDouble(LB.getText()); 
 
     lc=Double.parseDouble(LC.getText()); 
 
     
 
     if (la==lb && la==lc){ 
 
     t=("Equilatero"); 
 
    }else if (la==lb || lb==lc || la==lc) { 
 
     t=("Isósceles"); 
 
    }else if (la!=lb || lb!=lc || la!=lc) { 
 
     t=("Escaleno");  
 
    } 
 
    if (lb+lc>la && la+lc>lb && la+lb>lc){ 
 
    a=Math.sqrt((la+lb+lc)*(-la+lb+lc)*(la-lb+lc)*(la+lb-lc)/16); 
 
    p=la+lb+lc; 
 
    //A.setText("El area del triangulo "+t+" es ("+a+")."); 
 
    A.setText("El triangulo "+t+" tiene un area de ("+a+") y un perimetro de ("+p+")."); 
 
    } else { 
 
    A.setText("Los valores ("+la+"), ("+lb+") y ("+lc+") no corresponden a los lados de un triangulo."); 
 
    } 
 
    }     

+0

你有沒有爲每個圖像已經imageicons? –

+0

代碼審查項目:您的變量名稱太短,無法對閱讀此內容的其他人有意義。像'la','lb','lc','a'等名稱使您的代碼非常難以理解。 –

+0

另一個檢查項目:使用以大寫字母開頭的變量名稱不遵循[Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html),所以除非'LA','LB '等都是類,他們不應該以大寫字母開頭。 –

回答

0

假設你已經知道如何爲圖像創建imageIcons,所有你需要做的就是添加一個JPanel到你的框架,然後添加一個JLabel了這一點。然後根據字符串的結果,將jlabel的圖標設置爲相應的圖像。

例如

//create panel and jlabel 
JPanel panel = new JPanel(); 
JLabel label = new JLabel(); 

//add the label to the panel, and the panel to the frame. 
panel.add(label); 
yourFrame.add(panel); 

//Check what image you want 
if(t.equals("Equilatero")){ 
    label.setIcon(example1Image); 
else if(t.equals.... 
1

首先,這是一個痛苦的一個JFrame設置圖像......你可以做的而不是更容易的是創建一個JLabelJPanel並設置自己的形象,然後添加JLabelJPanelJFrame

話雖這麼說,你可以做一個switch語句來找出哪些類型的三角形的結果如下:

JFrame frame = new JFrame(); 
JLabel label = new JLabel(); //or JPanel if that's what you prefer 
ImageIcon equil = new ImageIcon("filepath/to/this/image"); 
ImageIcon escal = new ImageIcon("filepath/to/this/image"); 
ImageIcon isosc = new ImageIcon("filepath/to/this/image"); 
frame.add(label); 
switch(t) { 
     default: { 
      label.setIcon(null); 
     } 

     case "Equilatero": { 
      label.setIcon(equil); 
     } 

     case "Escaleno": { 
      label.setIcon(escal); 
     } 

     case "Isosceles": { 
      label.setIcon(isosc); 
     } 
    }