gpt4 book ai didi

java - 将最终变量传递给 MouseListener 方法并返回结果

转载 作者:行者123 更新时间:2023-12-01 13:36:36 25 4
gpt4 key购买 nike

我正在努力处理这段代码,我想单击由 JPanel 对象创建的网格单元格之一,并在该单元格中显示一个带有该单元格索引的标签。我创建了一个方法来添加最终变量并返回带有该标签的 JPanel。它不起作用。我怎样才能做到这一点?

 public MyTest01(int width, int length) { //constructor

frame.setLayout(new GridLayout(width, length)); //set layout
JPanel temp = null;
JLabel l;

for (int y = 0; y < length; y++) {
for (int x = 0; x < width; x++) {
temp = new JPanel();
temp.setBorder(new LineBorder(Color.black, 1));
temp=doStuff(temp,x,y);
frame.add(temp);
}
}

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}

public static JPanel doStuff( final JPanel temp,final int x, final int y) {

MouseListener mouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
JLabel l = new JLabel("("+x+" - "+y+")");
temp.add(l);

}
};
return temp;
}

最佳答案

  1. 您永远不会将监听器添加到 JPanel
  2. 添加组件 (JLabel) 后,您需要重新验证重新绘制JPanel

    MouseListener mouseListener = new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent mouseEvent) {
    JLabel l = new JLabel("(" + x + " - " + y + ")");
    temp.add(l);
    temp.revalidate();; <-------- revalidate
    temp.repaint(); <-------- repaint
    }
    };
    temp.addMouseListener(mouseListener); <-------- add listener
    return temp;
<小时/>

这是工作代码

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class MyTest {

JFrame frame = new JFrame();

public MyTest(int width, int length) { //constructor

frame.setLayout(new GridLayout(width, length)); //set layout
JPanel temp = null;
JLabel l;

for (int y = 0; y < length; y++) {
for (int x = 0; x < width; x++) {
temp = new JPanel();
temp.setBorder(new LineBorder(Color.black, 1));
temp = doStuff(temp, x, y);
frame.add(temp);
}
}

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

public void run() {
new MyTest(3, 3);
}
});
}

public static JPanel doStuff(final JPanel temp, final int x, final int y) {

MouseListener mouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
JLabel l = new JLabel("(" + x + " - " + y + ")");
temp.add(l);
temp.revalidate();;
temp.repaint();
}
};
temp.addMouseListener(mouseListener);
return temp;
}
}

关于java - 将最终变量传递给 MouseListener 方法并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21225094/

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