我對Java很新(約2周),並且試圖設置JLabel的文本。唯一的問題是我在另一個課程中進行計算,我不知道如何引用我已經創建的Jlabel。這是兩個有問題的課程。在運行時設置JLabel文本
package fightsim;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FightSimPane extends JPanel {
FightManager FightManager = new FightManager();
/**
* Create the panel.
*/
public FightSimPane() {
setLayout(new MigLayout("", "[][][][][][][][][][]", "[][][][]"));
JLabel lblChampionleft = new JLabel("ChampionLeft");
add(lblChampionleft, "cell 1 3");
JButton btnGo = new JButton("Go");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
FightManager.startFight();
FightManager.runTheFight();
}
});
add(btnGo, "cell 5 3");
JLabel lblChampionright = new JLabel("ChampionRight");
add(lblChampionright, "cell 9 3");
}
public void setLeftChampionLabel(String s){
//not able to reference Jlabel lblChampionLeft here???
System.out.println("Setting Left Champion text to"+s);
}
public void setRightChampionLabel(String s){
//not able to reference Jlabel lblChampionRight here???
System.out.println("Setting Right Champion text to"+s);
}
}
而試圖設置標籤的類。
package fightsim;
public class FightManager {
Champion LeftChamp = new Champion();
Champion RightChamp = new Champion();
public FightManager() {
}
Thread LeftChampThread = new Thread(LeftChamp);
Thread RightChampThread = new Thread(RightChamp);
;
public void startFight() {
LeftChamp.setHealth(200);
RightChamp.setHealth(300);
LeftChamp.setATKsp(1000);
RightChamp.setATKsp(1000);
LeftChamp.setAD(20);
RightChamp.setAD(20);
}
public void runTheFight() {
System.out.println("Starting Threads");
LeftChampThread.start();
RightChampThread.start();
while ((LeftChamp.getHealth() > 0) && (RightChamp.getHealth() > 0)) {
if (RightChamp.isReadyToAttack()) {
LeftChamp.setHealth(LeftChamp.getHealth() - RightChamp.getAD());
RightChamp.setNotReady();
System.out.println("Setting Left Champion test to"
+ Integer.toString(LeftChamp.getHealth()));
// This is where I'd like to update the left Jlabel in
// FightSimPane
}
if (LeftChamp.isReadyToAttack()) {
RightChamp
.setHealth(RightChamp.getHealth() - LeftChamp.getAD());
LeftChamp.setNotReady();
System.out.println("Setting Right Champion test to"
+ Integer.toString(RightChamp.getHealth()));
// This is where I'd like to update the right Jlabel in
// FightSimPane
}
}
}
}
所以,問題...我如何讓我的FightManager類訪問和更改了的JLabel我FightSimPane類/ GUI。在此先感謝,如果這是一個愚蠢的問題,很抱歉。我對編程非常陌生,我仍然試圖將其全部納入其中。有了這些說法,其他任何建議都會很棒。謝謝!
好,幫助,現在我的問題是與setRightChampionLabel(String s)將和setLeftChampionLabel(String s)已方法。是否有任何理由我不能把lblChampionleft.setText(s);在那裏? –
@ThadBlankenship:是的,請不要在方法或構造函數中聲明JLabels!這樣他們的可見性就受限於相同的方法或構造函數。相反,將這些傢伙聲明爲非靜態類字段,並允許它在整個課程中可見。這與Swing無關,而是基本的Java變量範圍101. –
啊,我使用的是windowbuilder,它在構造函數中聲明瞭它們。那是怎麼回事? –