I have a problem with painting a rectangle on Mac. The code works on windows and a rectangle was painted on the Frame, but on mac the Frame appeared without the rectangle. I compiled the exact same code on both platforms.
Here is the code:
mainClass.java
import javax.swing.JFrame;
import java.awt.Rectangle;
public class mainClass
{
public static void main(String[] args)
{
JFrame window = new JFrame();
window.setSize(640, 480);
window.setTitle("New Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
drawingComponent DC = new drawingComponent();
window.add(DC);
}
}
drawingComponent.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Rectangle;
public class drawingComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle rect1 = new Rectangle(5, 5, 100, 200);
g2.draw(rect1);
}
}
They are saved onto 2 different .java files. I only compiled the mainClass.java on both platforms.
Any help is appreciated!
The last thing you should do is set the frame visible as that is the point where the painting happens. If you set visible first then modify the components you will not see the changes until the screen is repainted. Repainting will occur when the screen is invalidated for some reason.
Precisely why this is noticeable on the mac I cannot quite say, maybe some small difference in the JVM's implementation. If you have to update the UI after it is visible you can revalidate it to cause it to be repainted properly. This answer has some further details.