Swing not drawing on Mac

自闭症网瘾萝莉.ら 提交于 2019-12-24 05:51:01

问题


I am trying to draw an incredibly basic shape using swing in Java, however for some reason it does not seem to be working. This is code that I downloaded from my lecturer that he showed us in a lecture, but when I run it the window opens but nothing is drawn and I have no idea why.

package graphicsEx;

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class Lecture1Example extends JPanel{
    // This is where the JPanel gets (re-)painted when the screen is refreshed.
    public void paintComponent(Graphics g) {
        // Cast to Graphics2D for more features.        
        Graphics2D g2D = (Graphics2D) g;

        Rectangle2D rect = new Rectangle2D.Double(20,30,40,50);
        g2D.setColor(Color.red);
        g2D.draw(rect);
        g2D.fill(rect); 
    }

    public static void main(String args[]) {
        JFrame frame = new JFrame("Playing with Graphics");
        frame.setSize(500, 400);
        frame.setVisible(true);
        frame.setContentPane(new Lecture1Example());        
    }
}

I am using the Eclipse IDE.


回答1:


Dear user1821475's lecturer:

  • Swing GUI objects should be constructed and manipulated only on the event dispatch thread.

  • "Subclasses of Swing components which have a UI delegate (vs. direct subclasses of JComponent), should invoke super.paintComponent() within their paintComponent override.

  • "As a convenience add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary."

  • The outermost Container should be setVisible() only after invoking pack() and other methods affecting geometry.



来源:https://stackoverflow.com/questions/14265183/swing-not-drawing-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!