简体   繁体   中英

How to create a shortcut key for a JLabel?

enter image description here

I have a list JLabel . I want when click a label content display in JTextArea the same. Why when I click the label, the text area does not display?

The code:

   jLabel0.setText(namelist.get(0));
   jLabel1.setText(namelist.get(1));
   jLabel2.setText(namelist.get(2));
   jLabel3.setText(namelist.get(3));
   jLabel4.setText(namelist.get(4));
   jLabel5.setText(namelist.get(5));
    //String  b[]={"jLabel4","jLabel5","jLabel7","jLabel8","jLabel9","jLabel10"};
   for (int i=0;i<k;i++){
    
   String f=String.valueOf(i);
   JLabel jlb = new JLabel("jLabel"+f);
   String Af=file_list.get(i);
   FileReader F=new FileReader(Af);
   jlb.addMouseListener(new MouseListener(){
        public void mouseReleased(MouseEvent e) {
         }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseClicked(MouseEvent e) {
            if(e.getClickCount()==1)
            {
               
                try {
                    jTextArea3.read(F,"");
                } catch (IOException ex) {
                    Logger.getLogger(FAKENEWS.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
           
        }
    });
   }

You can simply achieve it using JButton and just by making the button look like a label. You will want to do the following once you have created the button:

     setFocusPainted(false);
     setMargin(new Insets(0, 0, 0, 0));
     setContentAreaFilled(false);
     setBorderPainted(false);
     setOpaque(false);

You may want to exclude setFocusPainted(false) if you want it to actually paint the focus (eg dotted line border on Windows look and feel).

And after that you may use the button event handlers to do your desired action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM