[英]java - highlighting only one field
I want to make my code highlights the square on which I click (this works). 我想使我的代码突出显示我单击的正方形(此方法有效)。 I do not know how to do that when you click on another square previous died and lights up a new one.
我不知道该怎么做,当您单击另一个先前死掉的方块并点亮一个新的方块时。 How to improve the method mouseClicked?
如何改善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
}
}
}
Eg in App class you can have field which is table of CustomPanels ( private CustomPanel[] myCustomPanels
and another field - integer private int highlightedOne = -1
which will point index of element which is highlighted. 例如,在App类中,您可以具有作为CustomPanels表的字段(
private CustomPanel[] myCustomPanels
以及另一个字段-整数private int highlightedOne = -1
,它将指向突出显示的元素的索引。
Then in method mouseClicked
you can do something like that: 然后在方法
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);
}
Field section: 栏目部分:
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);
}
...
Alternatively you can use List instead of table - you don't need then pass size to it on beginning. 或者,您可以使用列表而不是表-您不需要在开始时将大小传递给它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.