Merp
Merp

Reputation: 65

Add two JPanels in different position on JApplet

I am trying to add two JPanel objects in different position on JApplet. But this code throws exception:

java.lang.IllegalArgumentException: illegal component position

Will anyone correct this code?

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

public class TwoPanel extends JApplet {

    JPanel p1,p2;
    JLabel l1,l2;

    @Override
    public void init()
    {
        p1=new JPanel();
        p2=new JPanel();
        p1.setLayout(new FlowLayout());
        p2.setLayout(new FlowLayout());
        l1=new JLabel("Panel 1");
        l2=new JLabel("panel 2");
        p1.add(l1,0,0);
        p2.add(l2,100,100);
        add(p1);
        add(p2);
        p1.setFocusable(true);
        p2.setFocusable(true);
    }
}

Exception

java.lang.IllegalArgumentException: illegal component position
    at java.awt.Container.addImpl(Container.java:1080)
    at java.awt.Container.add(Container.java:998)
    at TwoPanel.init(TwoPanel.java:25)
    at sun.applet.AppletPanel.run(AppletPanel.java:435)
    at java.lang.Thread.run(Thread.java:744)

Upvotes: 3

Views: 221

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

p1.add(l1,0,0);

This is not how to position things in panels. Use a border for white space.

enter image description here

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

/* <applet code=TwoPanel width=400 height=300></applet> */
public class TwoPanel extends JApplet {

    JPanel p1,p2;
    JLabel l1,l2;

    @Override
    public void init()
    {
        // JApplet defaults to BorderLayout
        System.out.println(getLayout());
        p1=new JPanel();
        p2=new JPanel();
        p1.setLayout(new FlowLayout());
        p2.setLayout(new FlowLayout());
        l1=new JLabel("Panel 1");
        l2=new JLabel("panel 2");
        p1.add(l1);
        p1.setBackground(Color.RED);
        p2.add(l2);
        p2.setBackground(Color.GREEN);
        p2.setBorder(new EmptyBorder(100,100,100,100));
        // a panel added to a BorderLayout with no constraint ends in the CENTER
        add(p1, BorderLayout.PAGE_START);
        // but the CENTER only shows ONE component.
        add(p2);
        p1.setFocusable(true);
        p2.setFocusable(true);
    }
}

More Generally

Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.

Upvotes: 2

Related Questions