There were several problems:
- Your
label1 was hidden by running the JLabel label in the constructor. You basically declared another label1 variable in your constructor, which hid it in the class itself. - Your label was visible at startup - I used
label.setVisible(false) for the test, but you might want otherwise
I also added the creation of Image aside, as I didn’t have an image, so uncomment this and change as needed.
Here's the full working version:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LearnAppMain extends JFrame implements ActionListener { // Define variables public JButton button1; public JLabel label1; public JTextField field1; private Image image1; private String apple = "apple.jpg"; public LearnAppMain() { //ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple)); //JLabel label1 = new JLabel(image1); label1 = new JLabel("hello"); label1.setVisible(false); button1 = new JButton("A"); button1.addActionListener(this); field1 = new JTextField(10); // Create layout setLayout(new FlowLayout()); // create Container final Container cn = getContentPane(); cn.add(button1); cn.add(field1); cn.add(label1); // setLayout(new FlowLayout()); setSize(250, 250); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (e.getSource() == button1) { label1.setVisible(true); field1.setText("Apple"); } } public static void main(String[] args) { new LearnAppMain(); } }
I would suggest using separate (usually inner classes) ActionListener instances instead of overriding actionPerformed . See this for a similar example if you are interested:
Also, if you are using this in a larger application (i.e., not just experimenting or prototyping), make sure that all Swing code is running on EDT.
You usually use SwingUtilities.invokeLater for this purpose.
Hope this helps.
source share