在编写代码时,可以使用以下方法来保留右键点击时的当前选择:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RightClickExample extends JFrame {
private JLabel label;
public RightClickExample() {
label = new JLabel("Right click to select");
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
// 保存当前选择的逻辑
System.out.println("Right click: " + label.getText());
}
}
});
setLayout(new FlowLayout());
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(RightClickExample::new);
}
}
在上面的示例中,我们创建了一个带有标签的简单窗口,当用户右键点击标签时,会在控制台上打印出当前选择的文本。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RightClickExample extends JFrame {
private JLabel label;
public RightClickExample() {
label = new JLabel("Right click to select");
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
// 保存当前选择的逻辑
System.out.println("Right click: " + label.getText());
}
}
};
label.addMouseListener(mouseAdapter);
setLayout(new FlowLayout());
add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(RightClickExample::new);
}
}
在上述示例中,我们将鼠标适配器分配给标签的鼠标监听器,以便在右键点击时执行保存当前选择的逻辑。
无论使用哪种方法,你都可以在适当的事件处理程序或适配器中执行保存当前选择的逻辑。你可以根据具体的需求来扩展这些示例代码。
上一篇:保留由$group操作折叠的字段