Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Very simple label/button question in Swing

Status
Not open for further replies.

LaPluma

Programmer
Feb 3, 2002
139
DE
Hello

I have some Java code which I would like to develop, but I am not sure how to add a label or a submit button.

To the following code, why can't I simply add:

JButton button = new JButton ("Click to open"); after the:

JButton button = new JButton ("Click to close");????

Why won't this line add another button?

I would appreciate any help.

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

public class SwingFrame
{
public static void main (String args[])
throws Exception
{
JFrame frame = new JFrame("Swing Demo");
JLabel label = new JLabel("Swing Version");
JButton button = new JButton ("Click to close");


button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
System.exit(0);


}
});

// Get content pane
Container pane = frame.getContentPane();

// Set layout manager
pane.setLayout( new FlowLayout() );

// Add to pane
pane.add( label );
pane.add( button );
frame.pack();

// Center the frame
Toolkit toolkit = Toolkit.getDefaultToolkit();

// Get the current screen size
Dimension scrnsize = toolkit.getScreenSize();

// Get the frame size
Dimension framesize= frame.getSize();

// Set X,Y location
frame.setLocation ( (int) (scrnsize.getWidth()
- frame.getWidth() ) / 2 ,
(int) (scrnsize.getHeight()
- frame.getHeight()) / 2);

frame.setVisible(true);




}
}
 
You need to add it to the content pane. Just creating a new JButton does not automatically add it to the pane. Try:

// Add to pane
pane.add( label );
pane.add( button );
// add this line
pane.add( newButton );
frame.pack();

-gc
 
Hello godcomplex

I am grateful for your reply. Thanks to you, I have
learnt that simply creating a new JButton does not automatically add it to the pane.

I added your suggested code and got this:

C:\jdk1.3.1\bin>javac SwingFrame.java
SwingFrame.java:57: cannot resolve symbol
symbol : variable newButton
location: class SwingFrame
pane.add( newButton );
^
1 error

Please talk me through it.

Best wishes

 
You have two JButton "button"'s you need one to be called newButton.


-LesP-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top