Saturday, 8 June 2013

JPanel elements are not appearing

JPanel elements are not appearing

I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
    private static int zip;
    public static int AskZip() {
        JFrame zaWindow = new JFrame("What Zipcode");
        zaWindow.setSize(200, 300);
        JPanel jp = new JPanel();
        final JTextField tf = new JTextField("Enter Zip Here");
        JLabel label = new JLabel();
        JButton button = new JButton("Get Weather");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String sZip = tf.getText();
                int rZip = 0;
                try {
                    if (sZip.length() != 5) {
                        JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
                    } else {
                        rZip = Integer.parseInt(sZip);
                    }
                } catch (NumberFormatException arg) {
                    JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
                }
                zip = rZip;
            }
        });
        label.setText("What is your zipcode?");
        jp.add(label);
        jp.add(tf);
        jp.add(button);
        zaWindow.add(jp);
        return zip;
    }

No comments:

Post a Comment