0

我正在制作一个应用程序,其中包含一些带有文本(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);
}
}

您必须开始单击底部的组合,您会在控制台中看到焦点丢失。单击灰色矩形,将获得焦点。单击矩形内的组合,矩形会立即失去焦点并获得焦点,因此无法选择项目。当我与它的组合框交互时,我不想改变矩形的焦点。

4

0 回答 0