gpt4 book ai didi

java - 修改 addMouseListener()

转载 作者:行者123 更新时间:2023-12-01 23:50:21 29 4
gpt4 key购买 nike

这是我的按钮代码 onclick 我希望我的程序等待用户单击一个 JPanel,并且当用户单击 JPanel 时,它应该在控制台上打印其名称。

此按钮代码未显示输出

  JPopupMenu popupMenu_1 = new JPopupMenu();

JMenuItem mntmOneToOne = new JMenuItem("One to One");




mntmOneToOne.setIcon(new ImageIcon("C:\\Users\\Ashad\\Desktop\\oneToone.png"));
popupMenu_1.add(mntmOneToOne);

OneToOne.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent arg0)
{
MouseListener Listen= new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
String name=new String();
JPanel panel = (JPanel) me.getSource();

// name = panel.getName();

System.out.println(panel.getName());
}
};
}

});

最佳答案

for better help sooner post an SSCCE, short, runnable, compilable,

因为在我的 SSCCE 中工作,以及答案

This is my button Code onclick i want my program to wait for the user to click one JPanel and as the user clicks the JPanel it should print its name on console.

问题必须存在于您的代码的其余部分,

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class MyGridLayout {

public MyGridLayout() {
JPanel bPanel = new JPanel();
bPanel.setLayout(new GridLayout(10, 10, 2, 2));
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
JPanel b = new JPanel() {
private static final long serialVersionUID = 1L;

@Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
};
b.putClientProperty("column", row);
b.putClientProperty("row", col);
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JPanel btn = (JPanel) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
});
b.setBorder(new LineBorder(Color.blue, 1));
bPanel.add(b);
}
}
JFrame frame = new JFrame("PutClientProperty Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(bPanel);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyGridLayout myGridLayout = new MyGridLayout();
}
});
}
}

关于java - 修改 addMouseListener(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389083/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com