我想让我的代码突出显示我点击的方块(这是有效的)。当你点击另一个前方死亡并点亮一个新的方块时,我不知道该怎么做。 如何改进mouseClicked方法?
public class App
{
public static void main(String[] args)
{
new App();
}
App()
{
JFrame jFrame = new JFrame("Mouse Hover Demo");
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setLayout(new GridLayout(5,5));
for(int i=0;i<25;i++)
{
jFrame.add(new CustomPanel(i));
}
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
class CustomPanel extends JPanel implements MouseListener
{
/**
*
*/
boolean isHighlighted;
int postion;
int tab[];
private static final long serialVersionUID = 1L;
Border blackBorder = BorderFactory.createLineBorder(Color.BLACK);
CustomPanel(int postion)
{
this.postion = postion;
addMouseListener(this);
setBorder(blackBorder);
setFocusable(true);
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(50, 50);
}
@Override public void mouseClicked(MouseEvent e)
{
System.out.println(this.postion);
setBackground(Color.black);
}
@Override public void mousePressed(MouseEvent e){}
@Override public void mouseReleased(MouseEvent e){}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
答案 0 :(得分:0)
E.g。在App类中,您可以拥有CustomPanels表(private CustomPanel[] myCustomPanels
)和另一个字段 - 整数private int highlightedOne = -1
的字段,它将指向突出显示的元素的索引。
然后在方法mouseClicked
中你可以做类似的事情:
@Override public void mouseClicked(MouseEvent e)
{
System.out.println(this.postion);
if (highlightedOne != -1)
myCustomPanels[highlightedOne].setBackground(Color.white);
highlightedOne = this.position;
setBackground(Color.black);
}
现场部分:
public class App
{
private CustomPanel[] myCustomPanels = new CustomPanel[25];
private int highlightedOne = -1;
public static void main(String[] args)
{
new App();
}
App()
{
JFrame jFrame = new JFrame("Mouse Hover Demo");
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setLayout(new GridLayout(5,5));
for(int i=0;i<25;i++)
{
CustomPanel toAdd = new CustomPanel(i);
myCustomPanels[i] = toAdd;
jFrame.add(toAdd);
}
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
...
或者你可以使用List而不是table - 你不需要在开始时将大小传递给它。