Question

(This program isn't really going to end up doing anything I'm just using this to learn/experiment)

When I run my code I wanted one class to paint a black circle and another class to paint a blue circle that intersects it. But the way I have it now when an instance of Class2 is added it overwrites Class1 in the Frame.

I can see what's going wrong I'm just not sure on how to fix it.

Is it possible to do this or are you supposed to just do everything under the same paint()?

public class Practice{
    public static GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    public static final int dWidth = gd.getDisplayMode().getWidth();
    public static final int dHeight = gd.getDisplayMode().getHeight();  

   public static void main(String[] args){
       heyo();
       }

   public static void heyo(){
       JFrame window = new JFrame();
       Class1 obj1 = new Class1();
       Class2 obj2 = new Class2();

        window.setSize(dWidth, dHeight);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.add(obj1);
        window.add(obj2);

        window.setVisible(true);
       }

}

public class Class1 extends JComponent{

    public void paint(Graphics b){
        Graphics2D brush = (Graphics2D)b;
        brush.setColor(Color.black);

        brush.drawOval(100, 100, 50, 50);

    }

}

public class Class2 extends JComponent{

    public void paint(Graphics c){
        Graphics2D brush = (Graphics2D)c;
        brush.setColor(Color.blue);

        brush.drawOval(200, 200, 50, 50);

    }

}
Était-ce utile?

La solution

  • JFrame by default use BorderLayout and you have added two components at the center.

  • Use JPanel and add the components in the JPanel first then finally add the JPanel in the JFrame

  • Don't override paint() method instead use paintComponent()

Here is the sample code:

class Class1 extends JComponent {

    @Override
    public void paintComponent(Graphics b) {
        super.paintComponent(b);
        ...    
    }

}

class Class2 extends JComponent {

    @Override
    public void paintComponent(Graphics c) {
        super.paintComponent(c);
        ...    
    }

}


public static void heyo() {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame window = new JFrame();

            JPanel panel = new JPanel(new GridLayout(1, 2));
            Class1 obj1 = new Class1();
            Class2 obj2 = new Class2();
            panel.add(obj1);
            panel.add(obj2);
            ...

            window.getContentPane().add(panel);
            window.setVisible(true);
        }
    });
}

enter image description here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top