我在如何使鼠标退出并在def update_version_strings(file_path, new_version):
version_regex = re.compile(r"(^_*?version_*?\s*=\s*['\"])(\d+\.\d+\.\d+)", re.M)
with open(file_path, "r+") as f:
content = f.read()
f.seek(0)
f.write(
re.sub(
version_regex,
lambda match: "{}{}".format(match.group(1), new_version),
content,
)
)
f.truncate()
的{{1}}上输入鼠标有问题,该{1}在1个单元格中包含2个面板。
我不知道如何在网格布局中输入哪个单元格,有功能吗?
我在容器上有5行3列的网格布局,而我想要的是对所有单元格的鼠标侦听器,因此当我输入单元格时,它会说由于鼠标侦听器而输入了哪个单元格。 / p>
有任何线索吗?
答案 0 :(得分:1)
MouseEvent.getComponent()
将返回生成事件的组件。如果代码将鼠标侦听器添加到网格中的每个面板,则很容易找出触发该事件的面板。
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MousePanelArrayTest {
private final JComponent ui = new JPanel(new BorderLayout(4, 4));
MouseListener mouseListener;
MousePanelArrayTest() {
initUI();
}
public final void initUI() {
mouseListener = new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Component c = e.getComponent();
c.setBackground(Color.BLACK);
}
@Override
public void mouseExited(MouseEvent e) {
Component c = e.getComponent();
c.setBackground(Color.WHITE);
}
};
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel gridPanel = new JPanel(new GridLayout(0, 5, 4, 4));
ui.add(gridPanel);
for (int ii=0; ii<20; ii++) {
gridPanel.add(getPanel());
}
}
private JPanel getPanel() {
JPanel p = new JPanel();
p.addMouseListener(mouseListener);
p.setBorder(new EmptyBorder(10, 20, 10, 20));
return p;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
MousePanelArrayTest o = new MousePanelArrayTest();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}````
答案 1 :(得分:0)
一种方法是在鼠标进入网格布局时获取鼠标的位置,并计算该位置所属的单元格。因为网格布局仅允许使用相同大小的单元格,所以可以轻松计算出该大小。用伪代码:
event = the mouse event
position = event.getPosition()
panelPosition = position of the panel that includes the grid layout
relativePosition = [position.x - panePosition.x, position.y - panePosition.y]
//get width and height of the panel that includes the gridlayout
int width = pane.width
int height = pane.height
int numRows = gridlayout.getRows()
int numCols = gridlayout.getCols()
int cellx = relativePosition.x / (width / numRows)
int celly = relativePosition.y / (height / numCols)
//the cell where the mouse is is [cellx, celly]
在此处需要将MouseListener
添加到包含GridLayout
的面板中,因为您不能在布局本身中添加MouseListener
(但是布局将具有相同的尺寸与面板一样,所以没关系)。
另一种方法是将一个面板添加到gridlayout的每个单元中,并检查鼠标是否进入了其中一个面板(您知道该单元,因为您将它们添加到了布局中)。