簡體   English   中英

動態更新JLabel會導致GUI變形-調整窗口大小后可以工作

[英]Updating JLabel Dynamically causes GUI to distort - Works after resizing window

我有一個GUI。 GUI是具有Panel [Gridbaglayout]的JFrame。 該Gridbag布局具有3個不同的組件。 中間組件是panel [GridBagLayout],其中包含我正在談論的JLabel。 它還包含一個JScrollBar,當用戶移動該欄時,我從中獲取值並更新JLabel。

我用來獲取值並更新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() + "%");
    }
}

}

編輯8/15/2017,11:30 AM:我找到了一種解決方法。 我認為,自從我調整窗口大小以來,它似乎會重新繪制自身並看上去正確。 我只是在每次在AdjustmentListener中調用setText之后放置jFrame.repaint()。 附帶一提,它看起來好像整個GUI都在“ Options JPanel”中重新繪制,如圖所示。

在Swing中, Listener是在UI線程上執行的。 也就是說,可以直接從adjustmentValueChangedactionPerformed等方法更新UI元素。

僅當從另一個線程啟動更新時,才必須使用SwingUtilities.invokeLater()和類似方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM