Swings JLabel, Image Icon, JTextField
Swings JLabel, Image Icon, JTextField
Exploring Swing
Some of the Swing component classes:
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try
{
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}
JTextFiel
•
d
Is the simplest Swing text component.
• Allows us to edit one line of text.
• Derived from JTextComponent.
JTextField(int cols)
JTextField(String str , int cols)
JTextField(String str)
String getText() - obtain the text currently in the text
field.
// Demonstrate JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() { public void run() { makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent
ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}