Cornelius Eanes's Programming Portal
Assignments (GUI)
[41] Using Swing for Input

Goal: Get user input using Swing.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: Using Swing for Input
/// File Name: SwingForInput.java
/// Date Finished: Oct 15, 2015

import javax.swing.*;

public class SwingForInput {

    public static void main(String[] args) {

        String name = JOptionPane.showInputDialog("Please enter your name.");
        String ageString = JOptionPane.showInputDialog("Please enter your age.");
        int age = Integer.parseInt(ageString);

        System.out.println("Hello, " + name + ".");
        System.out.println("Next year you'll be " + (age + 1) + " years old.");

    }

}

Output

[42] Boring Window

Goal: Learn how to initialize a basic Swing window.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: A Boring Window
/// File Name: BoringWindow.java
/// Date Finished: Oct 15, 2015

import javax.swing.*;

public class BoringWindow {

    public static void main(String[] args) {

        JFrame f = new JFrame("Boring Window");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setSize(300, 200);
        f.setLocationRelativeTo(null); // puts the window in the center of the screen
        f.setVisible(true);

    }

}

Output

[43] A Frame with a Panel with Some Writing

Goal: Create a JFrame with a custom-made JPanel.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: A Frame with a Panel with Some Writing
/// File Name: SimpleFrame.java
/// Date Finished: Oct 15, 2015

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

public class SimpleFrameApp {

    public static void main(String[] args) {

        new SimpleFrame().setVisible(true);

    }

}

class SimpleFrame extends JFrame {

    public SimpleFrame() {
        setTitle("A Simple Frame");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        getContentPane().add(new SimplePanel());
    }

}

class SimplePanel extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Hello world!", 20, 20);
    }
}

Output