我有一個GUI屏幕,它有一個標籤。我現在想用文本設置標籤,如下所示(Test
)。但它沒有得到更新。我認爲在下面的代碼中有一個錯誤,我在try塊中重新創建了一個FrameTest的新對象;將文本顯示到另一個類的標籤 - JFrame
FrameTest frame = new FrameTest();
frame.setVisible(true); //(the full code given below)
的完整代碼:注:下面的類是從的JFrame
import java.awt.BorderLayout;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
}
}
測試類
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
f.writeLabel("FFFFF");
}}
幫助延長,我怎樣才能得到文本"FFFFF"
顯示的標籤?
'的setBounds(100,100,450,300);'多少次,我們不得不說的呢?不要設置邊界 - 'pack()',然後'setLocationByPlatform(true)'。 –