我有一个带有多个面板的框架。每当我按下/释放/单击中心面板时,JLabel 都会显示我执行此类操作的次数和坐标。问题是窗口不会刷新,因此 JLabel 上的所有这些值都保持为 0。通常对于 PaintComponents,我会使用 repaint()
,但我没有使用此方法。
这是我应该“重新绘制”的代码段:
public void mousePressed(MouseEvent e) {
pressCounter++;
x = e.getX();
y = e.getY();
buildIt(); //this works, but doesn't do what i want it to do
}
调用buildIt()
实际上是有效的,但它会在每次操作后打开一个新窗口,而不是刷新原始窗口。我还在这里尝试了 revalidate()
和 removeAll()
,但它们似乎根本没有做任何事情。
那么如何刷新窗口?
以下是完整的代码供引用:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MouseMonitor extends JPanel implements MouseListener {
JFrame frame;
JPanel topPanel, centerPanel, bottomPanel;
JLabel pressLabel, releaseLabel, clickLabel, xLabel, yLabel;
int pressCounter = 0;
int releaseCounter = 0;
int clickCounter = 0;
int x, y;
void buildIt() {
frame = new JFrame("Mouse Monitor");
topPanel = new JPanel();
centerPanel = new JPanel();
bottomPanel = new JPanel();
pressLabel = new JLabel("pressed: " + pressCounter);
releaseLabel = new JLabel("released: " + releaseCounter);
clickLabel = new JLabel("clicked: " + clickCounter);
xLabel = new JLabel("x-coordinate: " + x);
yLabel = new JLabel("y-coordinate: " + y);
frame.add(topPanel, BorderLayout.NORTH);
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
topPanel.add(pressLabel);
topPanel.add(releaseLabel);
topPanel.add(clickLabel);
bottomPanel.add(xLabel);
bottomPanel.add(yLabel);
pressLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
releaseLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
clickLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
xLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
yLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
Color color = new Color(193, 236, 255);
centerPanel.setBackground(color);
centerPanel.addMouseListener(this);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void mousePressed(MouseEvent e) {
pressCounter++;
x = e.getX();
y = e.getY();
buildIt();
}
public void mouseReleased(MouseEvent e) {
releaseCounter++;
}
public void mouseClicked(MouseEvent e) {
clickCounter++;
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public static void main(String[] args) {
new MouseMonitor().buildIt();
}
}
最佳答案
您不需要调用built()
方法来刷新框架或面板。为了达到您想要的目的,您只需更改标签上的文字即可。例如,考虑 mousePressed(MouseEvent e)
方法,取出 buildIt()
方法:
public void mousePressed(MouseEvent e) {
pressCounter++;
pressLabel.setText("pressed: " + pressCounter);
}
对每个方法都执行此操作,您就可以开始了。在 main
方法中维护代码。
关于java - 不使用 repaint()、revalidate() 刷新 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022706/