我有一個GUI。 GUI是一個帶有Panel [Gridbaglayout]的JFrame。這個網格包佈局有3個不同的組件。中間組件是一個面板[GridBagLayout],它具有我正在談論的JLabel。它還包含一個JScrollBar,我從中獲取數值並在用戶移動欄時更新JLabel。更新JLabel動態導致GUI扭曲 - 調整窗口大小後的作品
的代碼我使用來獲取值和更新的JLabel:
public class DrinkAdjustmentListener implements AdjustmentListener{
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
drinkLabel.setText("Percentage " + e.getValue() + "%");
}
}
編碼爲Android時,我明白了,主線程是UI線程爲好。隨着Swing我不相信這是事實,我不確定如何正確地更新GUI。這是好的,這是導致失真的其他事情,也許是佈局經理?
前:
後:
這是一些示例代碼運行展示什麼,我想要的目的。令人驚訝的是,它的工作。我將不得不做一個更長的例子來利用這個問題。
public class Gui {
private JLabel jLabel;
public void displayGui(){
JFrame jFrame = new JFrame();
jFrame.setSize(500,500);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setPreferredSize(new Dimension(400,400));
jLabel = new JLabel("Some Percentage 0%");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
mainPanel.add(jLabel,c);
JScrollBar jScrollBar = new JScrollBar();
jScrollBar.addAdjustmentListener(new MyAdjustmentListener());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
mainPanel.add(jScrollBar,c);
jFrame.add(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
}
public class MyAdjustmentListener implements AdjustmentListener{
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
jLabel.setText("Some Percentage " + e.getValue() + "%");
}
}
}
編輯2017年8月15日,11:30 AM: 我找到了一個解決方法。我想,自從我調整窗口大小時,它似乎重新繪製並看起來正確。每次在adjustListener中調用setText後,我只需要放入jFrame.repaint()。作爲一個側面說明,它看起來好像整個GUI都在圖中所示的「選項JPanel」中重繪。
請提供一個可運行的簡短示例([SSCCE](http://sscce.org)),因此我們也可以重現您的問題。 –
'更新JLabel動態導致GUI變形' - 我不知道「變形」是什麼意思。這就是爲什麼你需要發佈一個適當的[mcve]每個問題。 – camickr
@SergiyMedvynskyy @SergiyMedvynskyy這是我的例子..唯一的問題是,它的工作..我要去嘗試和利用問題 – TheAppFoundry