我正在创建一个带有文本(rectangleName)的'矩形'(myLabel)的应用程序。每当我点击该矩形时,就会显示一个组合框(nameComboBox)来更改它的名称。
所以这是该类的声明。
public class myLabel extends JLabel implements MouseListener,FocusListener{
//this.panel;
JComboBox nameComboBox;
String rectangleName;
我在该类中添加了一些焦点内容,因为您可以看到它实现了FocusListener。
我只想在重新聚焦时显示组合框,否则隐藏它。我遇到的问题是,当我选择一个矩形并显示组合框因为它是聚焦时,当我点击组合框时,矩形会失去焦点,因此它会隐藏组合框。有什么方法可以防止这种情况吗?
编辑:
回复@mKorbel,这是我的SSCCE
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class MyJLabel extends JLabel implements MouseListener,FocusListener{
JComboBox nameComboBox;
JPanel mainPanel;
String name;
public MyJLabel() {
this.setLocation(10,10);
this.setBounds(20, 20,200,200);
this.setBackground(Color.LIGHT_GRAY);
this.setFocusable(true);
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
setFont(getFont());
setText(this.name);
this.nameComboBox= new JComboBox(new String[] { "option1","option2","option3" });
this.nameComboBox.setBounds(40,40,100,50);
this.nameComboBox.setVisible(false);
this.addMouseListener(this);
this.addFocusListener(this);
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("focus gained");
this.nameComboBox.setVisible(true);
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("focus lost");
this.nameComboBox.setVisible(false);
}
@Override
public void mouseClicked(MouseEvent e) {
this.requestFocus();
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
MyJLabel myjl=new MyJLabel();
JFrame fr = new JFrame();
fr.setLayout(null);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox otherCombo = new JComboBox(new String[] { "otherOption1","otherOption2","otherOption3" });
otherCombo.setBounds(40,400,100,50);
fr.add(myjl.nameComboBox);
fr.add(myjl);
fr.add(otherCombo);
fr.setSize(300,500);
fr.setVisible(true);
}
}
您必须开始点击底部的组合,您将在控制台中看到焦点丢失。单击灰色矩形,将获得焦点。单击矩形内的组合,矩形将丢失并立即获得焦点,因此无法选择项目。当我与其组合框进行交互时,我不想改变矩形的焦点。