#java #swing #jlabel
#java #swing #jlabel
Вопрос:
Я поместил значок в JMenuItem
. Я хочу, чтобы этот значок отображался на a JLabel
, когда я нажимаю на JMenuItem
, как я могу этого добиться?
Это мой код:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package labwork5;
/**
*
* @author haseeb shah
*/
public class lab5part2frame extends javax.swing.JFrame {
/**
* Creates new form lab5part2frame
*/
public lab5part2frame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${icon}"), this, org.jdesktop.beansbinding.BeanProperty.create("iconImage"));
bindingGroup.addBinding(binding);
jLabel1.setIcon(jMenuItem1.getRolloverSelectedIcon());
jLabel1.setText("jLabel1");
jLabel1.setComponentPopupMenu(jMenuItem1.getComponentPopupMenu());
jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel1.addContainerListener(new java.awt.event.ContainerAdapter() {
public void componentRemoved(java.awt.event.ContainerEvent evt) {
jLabel1ComponentRemoved(evt);
}
});
jMenu1.setText("Mobile Networks");
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${icon}"), jMenu1, org.jdesktop.beansbinding.BeanProperty.create("actionCommand"));
bindingGroup.addBinding(binding);
jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenu1MouseClicked(evt);
}
});
jMenuItem1.setAction(java.swing.posticon(jLabel1));
jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/labwork5/province icon.jpg"))); // NOI18N
jMenuItem1.setText("Zain");
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jLabel1, org.jdesktop.beansbinding.ELProperty.create("${displayedMnemonic}"), jMenuItem1, org.jdesktop.beansbinding.BeanProperty.create("actionCommand"));
bindingGroup.addBinding(binding);
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Mobily");
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Gomo");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(113, Short.MAX_VALUE))
);
bindingGroup.bind();
pack();
}// </editor-fold>
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jLabel1ComponentRemoved(java.awt.event.ContainerEvent evt) {
}
private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {
this.transferFocus();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(lab5part2frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new lab5part2frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration
}
Комментарии:
1. Прочитайте раздел из руководства по Swing о том, как использовать значки , для рабочего примера добавления значка в JLabel. В вашем случае в ActionListener JMenuItem вам нужно будет 1) прочитать изображение 2) создать значок 3) добавить значок к ярлыку.
2. Используете ли вы JFormDesigner ?
Ответ №1:
Используйте jlabel.setIcon(Icon icon)
метод. Не забудьте использовать jlabel.revalidate()
и jlabel.repaint()
после обновления вашего графического интерфейса.