这是我的按钮代码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());
}
};
}
});
答案 0 :(得分:2)
要在SSCCE发布更快的帮助,简而言之, 可运行,可编辑,
因为在我的SSCCE中工作,以及
的答案这是我的按钮代码onclick我希望我的程序等待用户 单击一个JPanel,当用户单击它应该打印的JPanel时 它的名字在控制台上。
问题必须在你的其余代码中,
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();
}
});
}
}
答案 1 :(得分:1)
你在MouseListener mouseClicked方法中声明了一个MouseAdapter,它只是坐在那里,并没有做什么,因为没有做任何事情。如果要将MouseListener添加到面板,请执行以下操作:
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
JPanel panel = (JPanel) arg0.getSource();
System.out.println(panel.getName());
}
});