Panel

Panels allow you to organize portions of a largep mes interface within a frame, a dialog, or a window. Like frames (j ava. awt . Frame and j avax. swing. JFrame), panels extend the j ava . awt .Container class, which means that they can contain other components. However, they can't exist on their own but must be in the context of a window, dialog, or frame, or in the context of another panel contained in a top-level window (like Dialog,Frame, or Window).

Here's a JFC/Swing example of adding components with JPanel, in which every time the Add button is pressed another button is added to a panel. Import JPanel and JFrame from the javax.swifg package.

>>> from javax.swing import JPanel, JFrame, JButton

Create a frame variable in the global space of the main module. Also, create an instance of JPanel called pane, and initialize the count to (X

>>> frame = None >>> pane = JPanel() >>> count = 0

Define an add () function that takes the global variables pane,count, and frame into its local namespace and adds a button to the panel called Pane. add () also increments the count variable, which keeps track of how many buttons are added)

Define a remove () function that removes the last button. This method uses the count variable (which is in the module namespace) to determine the last button removed

Supply an Add button (addB) to add a button to ^hie pane and a Remove button (removeB) to remove a button. The event handlec fo a nhe Add button i s set to the add() function.

>>> addB = JButton ("Add", actionPerformed = add) >>> removeB = JButton("Remove", actionPerformed = remove) >>> pane.add(addB); pane.add(removeB) >>> count = 2

Create a frame, and sec its tttle to "P anel Demo." Set the content pane to the pane instance defined earlrer, and make the frame visible.

>>> frame=JFrame(title="Panel Demo", contentPane=pane, visible=1) >>> frame.pack()

Hit the Add button twice to add a third and a fourth button to the panel. Hit it two more times to add a fifth and a sixth button. Hit the Remove button twice to remove the fifth and sixth buttons. Hit the Add button a good 10 to 20 times, and then you can resize the fra me whh the mouse.

Was this article helpful?

0 0

Post a comment