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?