[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
RE: [platform-swt-dev] SWT 101
|
> From: Erik Poupaert
>
> Another remark to make is that this behaviour is natural. Imagine that
> setting the text of label would trigger the recalculation of its size, and
> trigger the recalculation of its container's size.
Don't want that. I just want the label to get replaced. Perhaps adding
GridLayouts will work. In Swing, I don't have to do this. Here's the same
program in Swing, which works exactly how I expect it to. It's also 20
lines shorter.
SOURCE:
import java.util.Hashtable;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PromptSwing {
// Resources
JFrame frame;
JPanel panel;
// Fields
JTextField f1;
JLabel f2;
public PromptSwing() {
}
public void run() {
init();
setLayout();
createWidgets();
show();
}
private void init() {
// Create a standard window
frame = new JFrame("Swing Me");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
doExit();
}
});
}
private void setLayout() {
// Create the layout for the widgets
panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
frame.getContentPane().add(panel);
}
private void createWidgets() {
// Create my widgets
panel.add(new JLabel("Item Number:"));
f1 = new JTextField(20);
panel.add(f1);
panel.add(new JLabel("Description:"));
f2 = new JLabel();
panel.add(f2);
JButton b1 = new JButton("Find");
panel.add(b1);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
doFind();
}
});
JButton b2 = new JButton("Exit");
panel.add(b2);
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
doExit();
}
});
}
private void doFind() {
String desc = getDescription(f1.getText());
if (desc == null)
{
f1.setForeground(Color.WHITE);
f1.setBackground(Color.RED);
f2.setText("Not Found");
f2.setForeground(Color.RED);
}
else
{
f1.setForeground(Color.BLACK);
f1.setBackground(Color.WHITE);
f2.setText(desc);
f2.setForeground(Color.BLACK);
}
}
private void doExit() {
System.exit(0);
}
private static final Hashtable items;
static {
items = new Hashtable();
items.put("DOG", "My Puppy");
items.put("CAT", "My Kitty");
items.put("OCTOPUS", "Calamari Kid");
}
private String getDescription(String item)
{
return (String) items.get(item);
}
private void show() {
// Final setup - size the display show it
frame.setSize(200, 100);
frame.setVisible(true);
}
public static void main(String[] args) {
new PromptSwing().run();
}
}