Question

In: Computer Science

import java.awt.*; import javax.swing.JButton; import javax.swing.JFrame; public class GridBagLayoutDemo { final static boolean shouldFill = true;...

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

public class GridBagLayoutDemo {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}

button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);

button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);

button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);

button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);

button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}

private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.
addComponentsToPane(frame.getContentPane());

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

I need someone to go through this program and right more comments that explain a lot more Please. from top to bottom Thanks

Solutions

Expert Solution

First let's have a look at the output

The code creates a java swing gui with 5 buttons placed at some specific places , such as shown above.

Three buttons are at top plced size by size , the fourth one is just below the three buttons and occupies teh entire width , the last adn teh fifth one is ateh bottom right corner.

These buttons expand or collapse as per the window size , now let's have a look at the code

Go through tehc ode , everything has been explained via comments in the code below

Code

//these three libraries are needed for creating the swing gui

import java.awt.*;

import javax.swing.JButton;

import javax.swing.JFrame;

//class

public class GridBagLayoutDemo {

    //declaring some constants varibles

    final static boolean shouldFill = true;

    final static boolean shouldWeightX = true;

    final static boolean RIGHT_TO_LEFT = false;

    //method which sets up the content pane

    public static void addComponentsToPane(Container pane) {

        if (RIGHT_TO_LEFT) {

            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

        }

        JButton button;

        //this means that the gui will be based on grid layout

        pane.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        if (shouldFill) {

            // natural height, maximum width

            //this specifies to fill any horizontal extra space ,

            c.fill = GridBagConstraints.HORIZONTAL;

        }

        //create the first button

        button = new JButton("Button 1");

        if (shouldWeightX) {

            c.weightx = 0.5;

        }

        //this means to fill any extra horizontal space

        c.fill = GridBagConstraints.HORIZONTAL;

        c.gridx = 0;//specifies that this button will be on the first coloumn

        c.gridy = 0;///specifes the row number

        pane.add(button, c);//add the button

        //second button

        button = new JButton("Button 2");

        c.fill = GridBagConstraints.HORIZONTAL;

        c.weightx = 0.5;

        c.gridx = 1;//column

        c.gridy = 0;//row

        pane.add(button, c); //place the button

        //thirs button

        button = new JButton("Button 3");

        c.fill = GridBagConstraints.HORIZONTAL;

        c.weightx = 0.5;

        c.gridx = 2;//column

        c.gridy = 0;//row

        pane.add(button, c);

        //forth button

        button = new JButton("Long-Named Button 4");

        c.fill = GridBagConstraints.HORIZONTAL;

        c.ipady = 40; // specifies the padding that is the gaps between the button name adn its surrounding

        c.weightx = 0.0;

        c.gridwidth = 3;//this specifies it to occupy the entire width

        c.gridx = 0;//column number

        c.gridy = 1;//row number

        pane.add(button, c);

        // the fifth button

        button = new JButton("5");

        c.fill = GridBagConstraints.HORIZONTAL;

        c.ipady = 0; // reset to default

        c.weighty = 1.0; // request any extra vertical space

        c.anchor = GridBagConstraints.PAGE_END; // bottom of space

        c.insets = new Insets(10, 0, 0, 0); // top padding

        c.gridx = 1; // aligned with button 2

        c.gridwidth = 2; // 2 columns wide

        c.gridy = 2; // third row

        pane.add(button, c);

    }

    //method which creates the GUI (places 5 buttons) and rednders it

    private static void createAndShowGUI() {

        // Create and set up the window.

        JFrame frame = new JFrame("GridBagLayoutDemo");//here we create the window adn also specify the title for it

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // this is teh default behaviour that we want when close button is clicked

        // Set up the content pane.

        addComponentsToPane(frame.getContentPane());

        // Display the window.

        frame.pack();

        frame.setVisible(true); //if not provided then the window won't be visible

    }

    //this is the main driver code the program

    //it is the first method that gets invoked when the jaav application is run

    public static void main(String[] args) {

        // Schedule a job for the event-dispatching thread:

        // creating and showing this application's GUI.

        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            //runnable has a predefined method run() which is invoked at the appropriate time

            public void run() {

                //call the method to craete teh respective gui and display it

                //createAndShowGUI is a static method and hence can be called directly , without having to specify class name

                createAndShowGUI();

            }

        });

    }

}

Screenshot


Related Solutions

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME = "bowler.txt"; public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading Data from file"); Scanner fileReader = new Scanner(new File(FILE_NAME)); System.out.printf("%-20s%-10s%-10s%-10s%-10s\n", "Sample Data", "Game 1", "Game 2", "Game 3", "Average"); int bowler = 1; while (fileReader.hasNext()) { String scores[] = fileReader.nextLine().split("\\s+"); double average = Integer.parseInt(scores[0]) + Integer.parseInt(scores[1]) + Integer.parseInt(scores[2]); average /= 3; System.out.printf("%-20s%-10s%-10s%-10s%-10.2f\n", "Bowler " + bowler, scores[0], scores[1], scores[2], average); bowler += 1; }...
import java.util.Scanner; public class Lab5 { public static void main(String[] args) { final char SIDE_SYMB =...
import java.util.Scanner; public class Lab5 { public static void main(String[] args) { final char SIDE_SYMB = '-'; final char MID_SYMB = '*'; Scanner scanner = new Scanner(System.in); String inputStr = ""; char choice = ' '; int numSymbols = -1, sideWidth = -1, midWidth = -1; do { displayMenu(); inputStr = scanner.nextLine(); if (inputStr.length() > 0) { choice = inputStr.charAt(0); } switch (choice) { case 'r': System.out.println("Width of the sides?"); sideWidth = scanner.nextInt(); System.out.println("Width of the middle?"); midWidth = scanner.nextInt();...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void main(String[] args) throws Exception { Crypto crypto = new BasicCrypto();        String welcome = "Hello 2043-er's! Let's try this again :-)"; System.out.println(welcome); // First, where are we? //Let's print out our current working directory        Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath(); System.out.println("Current Working Directory: " + cwd); // Read in our file to encrypt    byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt")); // Encrypt it and...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) {...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) { int N; Scanner keybd = new Scanner(System.in); int[] counts = new int[12];    System.out.print("Enter the number of trials: "); N = keybd.nextInt();    Random die1 = new Random(); Random die2 = new Random(); int value1, value2, sum; for(int i = 1; i <= N; i++) { value1 = die1.nextInt(6) + 1; value2 = die2.nextInt(6) + 1; sum = value1 + value2; counts[sum-1]++; }   ...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);    // parse the number of strings int numStrings = Integer.parseInt(sc.nextLine());    // parse each string String[] stringsArray = new String[numStrings]; for (int i = 0; i < numStrings; i++) { stringsArray[i] = sc.nextLine(); }    // print whether there are duplicates System.out.println(hasDuplicates(stringsArray)); }    private static boolean hasDuplicates(String[] stringsArray) { // TODO fill this in and remove the below line...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static void main(String[] args) {         PriorityQueue<Person> peopleQueue = new PriorityQueue<>();         Scanner s = new Scanner(System.in);         String firstNameIn;         String lastNameIn;         int ageIn = 0;         int count = 1;         boolean done = false;         System.out.println("Enter the first name, last name and age of 5 people.");         while(peopleQueue.size() < 5) {             System.out.println("Enter a person");             System.out.print("First Name: ");             firstNameIn...
Consider the following code: public class Example { public static void doOp(Op op) { boolean result...
Consider the following code: public class Example { public static void doOp(Op op) { boolean result = op.operation(true, false); System.out.println(result); } public static void main(String[] args) { doOp(new AndOperation()); doOp(new OrOperation()); } } main's output: false true Define any interfaces and/or classes necessary to make this output happen. Multiple answers are possible. You may not modify any of the code in Example.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT