Question

I'm trying to set the text in a label dynamically by calling the setText method whenever a button is clicked. Here is my code:

import java.awt.*;
import java.awt.event.*;

class Date {
    public static void main(String[] args) {
        new MainWindow();
    }
}

class MainWindow {
    static Label month = new Label();
    static Label day = new Label();
    static Button submit = new Button("Submit");

    MainWindow() {
        Frame myFrame = new Frame("Date Window");
        myFrame.setLayout(new FlowLayout());
        myFrame.add(month);
        myFrame.add(day);
        myFrame.add(submit);
        submit.addActionListener(new ButtonListener());

        myFrame.addWindowListener(new WindowListener());        
        myFrame.setSize(200, 200);
        myFrame.setVisible(true);
    }
}

class WindowListener extends WindowAdapter {
    @Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

class ButtonListener implements ActionListener  {
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == MainWindow.submit) {
            MainWindow.month.setText("12");
            MainWindow.day.setText("31");
        } 
    }
}

When I initialize the two Label objects without any arguments, the strings "12" and "31" that are passed to the setText method aren't visible on the screen when the submit button is clicked until I click on the window and drag to resize it. I've noticed this on a Mac only. On a PC, the strings are are visible but obscured until I resize the window. However, if I initialize the labels like this:

    static Label month = new Label("0");
    static Label day = new Label("0");

On the Mac, the strings appear as intended, however, they're obscured until the window is resized. What am I missing?

Was it helpful?

Solution

Calling validate() on the Frame as mentioned here solved the problem.

OTHER TIPS

Try repainting the frame or/and set enough space(setPreferredSize, setMininumSize)

Well, most of your posting are over a year old so I'll give you the benefit of the doubt. I never use AWT so I don't know what the problem is, but I'll suggest:

1) Name you classes properly. "Date" is already a class in the JDK. Choose a better name.

2) Try using Swing components instead of AWT.

3) Get rid of static variables from your class.

4) Get rid of the WindowListener to close the frame.

The code example you posted here is 10-15 years old. Try something newer. Start with the Swing tutorial for more recent examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top