我正在动态地向面板添加一些JLabel。当用户点击Label时,它应该返回它包含的文本。我正在尝试以下代码:
private JLabel l;
private JPanel A;
private void LoadLabels(){
A.setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gbc;
gbc = new java.awt.GridBagConstraints();
gbc.fill = java.awt.GridBagConstraints.BOTH;
gbc.anchor = java.awt.GridBagConstraints.CENTER;
gbc.weighty = 0;
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.insets = new java.awt.Insets(1, 1, 1, 1);
for(int gx = 0; gx<15; gx++){
JLabel Sold = label(String.valueOf(gx+1));
Sold.setBackground(Color.yellow);
gbc.gridx = gx;
gbc.gridy = 0;
gbc.weightx = .5;
A.add(Sold, gbc);
}
// JLabel is declared here:
private JLabel label(String x){
l = new JLabel(x);
l.setFont(new java.awt.Font("Tahoma", 0, 16));
l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
l.setOpaque(true);
l.setBorder(javax.swing.BorderFactory.createEtchedBorder());
l.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
l.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
lMouseClicked(evt);
}
});
return l;
}
//Now I am writing mouseClick event like this:
private void lMouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==l){
System.out.println(l.getText());
}
为什么这个鼠标事件总是返回最后一个JLabel文本? (输出总是14)我如何获得每个JLabel的实际值?请帮忙。
答案 0 :(得分:2)
您的private JLabel l
指向最后添加的JLabel
,它将仅返回最后一个标签中的文本。尝试创建数组并为每个创建的标签定义参考。
在代码中发现了很多错误,遵循正确的命名约定。 只需运行此代码并检查,只需为每个创建的JLabel创建引用。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Color;
class Test {
private int i;
private JPanel A;
private JFrame f;
private JLabel []l;
Test(){
f=new JFrame();
A=new JPanel();
f.setVisible(true);
f.setSize(800, 800);
f.setLayout(null);
f.add(A);
LoadLabels();
}
private void LoadLabels(){
A.setLayout(new java.awt.GridBagLayout());
l=new JLabel[15];
for(int gx = 0; gx<15; gx++){
l[gx]= label(String.valueOf(gx+1));
l[gx].setBackground(Color.yellow);
l[gx].setBounds(30*gx, 30, 30, 20);
f.add(l[gx]);
}
}
// JLabel is declared here:
private JLabel label(String x){
final JLabel l;
l = new JLabel(x);
l.setFont(new java.awt.Font("Tahoma", 0, 16));
l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
l.setOpaque(true);
l.setBorder(javax.swing.BorderFactory.createEtchedBorder());
l.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
l.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
System.out.println(l.getText());
}
});
return l;
}
public static void main(String []args){
new Test();
}
}
(或)
你可以再做一件事,
只需在代码中替换以下方法
即可 private void lMouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==l){
System.out.println(l.getText());
}
}
与
private void lMouseClicked(java.awt.event.MouseEvent evt) {
//This will refer to current JLabel being called
System.out.println(((JLabel)evt.getSource()).getText());
}