我有一个带有几个面板的框架。每当我按下/释放/单击中心面板时,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();
}
}
答案 0 :(得分:1)
您无需调用built()
方法来刷新框架或面板。出于您想要的目的,您只需更改标签上的文本即可。例如,考虑mousePressed(MouseEvent e)
方法,请取出buildIt()
方法:
public void mousePressed(MouseEvent e) {
pressCounter++;
pressLabel.setText("pressed: " + pressCounter);
}
对每种方法都这样做,你很高兴。在main
方法中维护代码。