我有一个图形用户界面。 GUI 是一个具有面板[Gridbaglayout] 的 JFrame。该网格袋布局有 3 个不同的组件。中间的组件是一个面板[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() + "%");
}
}
}
编辑 2017 年 8 月 15 日上午 11:30: 我找到了一个解决方法。我想,自从我调整窗口大小后,它似乎重新粉刷了自己并且看起来是正确的。我只是在每次在AdjustmentListener中调用setText之后放置jFrame.repaint()。作为旁注,看起来好像整个 GUI 在“Options JPanel”内重新绘制,如图所示。
最佳答案
在 Swing 中,监听器在 UI 线程上执行。也就是说,直接通过 adjustmentValueChanged
、actionPerformed
等方法更新 UI 元素是安全的。
仅当更新是从另一个线程发起时,您才必须使用 SwingUtilities.invokeLater()
和类似的方法。
关于java - 动态更新 JLabel 会导致 GUI 扭曲 - 在调整窗口大小后有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45687577/