import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ShapeApp { private JFrame frame; private JComboBox<String> shapeComboBox; private JTextField dimension1Field; private JTextField dimension2Field; private JButton drawButton; private JPanel drawingPanel; public ShapeApp() { // Initialize the GUI components frame = new JFrame("Shape Drawer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String[] shapes = {"Circle", "Square", "Triangle", "Rectangle", "Sphere", "Cube", "Cone", "Cylinder", "Torus"}; shapeComboBox = new JComboBox<>(shapes); dimension1Field = new JTextField(10); dimension2Field = new JTextField(10); drawButton = new JButton("Draw"); drawingPanel = new JPanel(); drawButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { drawShape(); } }); } private void drawShape() { String selectedShape = (String) shapeComboBox.getSelectedItem(); double dimension1 = parseDimension(dimension1Field.getText()); double dimension2 = parseDimension(dimension2Field.getText()); if (dimension1 == -1 || dimension2 == -1) { JOptionPane.showMessageDialog(frame, "Invalid dimension input. Please enter valid numeric values."); return; } // Clear previous drawings drawingPanel.removeAll(); drawingPanel.repaint(); // Draw the selected shape switch (selectedShape) { case "Circle": drawCircle(dimension1); break; case "Square": drawSquare(dimension1); break; case "Triangle": drawTriangle(dimension1); break; case "Rectangle": drawRectangle(dimension1, dimension2); break; case "Sphere": drawSphere(dimension1); break; case "Cube": drawCube(dimension1); break; case "Cone": drawCone(dimension1, dimension2); break; case "Cylinder": drawCylinder(dimension1, dimension2); break; case "Torus": drawTorus(dimension1, dimension2); break; default: JOptionPane.showMessageDialog(frame, "Invalid shape selected."); } } private double parseDimension(String input) { try { return Double.parseDouble(input); } catch (NumberFormatException e) { return -1; // Invalid input } } private void drawCircle(double radius) { drawingPanel.add(new CirclePanel(radius)); frame.validate(); frame.repaint(); } private void drawSquare(double sideLength) { drawingPanel.add(new SquarePanel(sideLength)); frame.validate(); frame.repaint(); } private void drawTriangle(double base) { drawingPanel.add(new TrianglePanel(base)); frame.validate(); frame.repaint(); } private void drawRectangle(double width, double height) { drawingPanel.add(new RectanglePanel(width, height)); frame.validate(); frame.repaint(); } private void drawSphere(double radius) { drawingPanel.add(new SpherePanel(radius)); frame.validate(); frame.repaint(); } private void drawCube(double sideLength) { drawingPanel.add(new CubePanel(sideLength)); frame.validate(); frame.repaint(); } private void drawCone(double radius, double height) { drawingPanel.add(new ConePanel(radius, height)); frame.validate(); frame.repaint(); } private void drawCylinder(double radius, double height) { drawingPanel.add(new CylinderPanel(radius, height)); frame.validate(); frame.repaint(); } private void drawTorus(double majorRadius, double minorRadius) { drawingPanel.add(new TorusPanel(majorRadius, minorRadius)); frame.validate(); frame.repaint(); } public void createAndShowGUI() { // Create and configure the main JFrame frame.setLayout(new BorderLayout()); JPanel inputPanel = new JPanel(); inputPanel.setLayout(new GridLayout(3, 2)); inputPanel.add(new JLabel("Select Shape:")); inputPanel.add(shapeComboBox); inputPanel.add(new JLabel("Dimension 1:")); inputPanel.add(dimension1Field); inputPanel.add(new JLabel("Dimension 2:")); inputPanel.add(dimension2Field); JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); controlPanel.add(drawButton); frame.add(inputPanel, BorderLayout.NORTH); frame.add(controlPanel, BorderLayout.CENTER); frame.add(drawingPanel, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { ShapeApp app = new ShapeApp(); app.createAndShowGUI(); }); } } class CirclePanel extends JPanel { private double radius; public CirclePanel(double radius) { this.radius = radius; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int circleRadius = (int) (radius * 10); // Scale up for better visualization g.drawOval(centerX - circleRadius, centerY - circleRadius, 2 * circleRadius, 2 * circleRadius); } } class SquarePanel extends JPanel { private double sideLength; public SquarePanel(double sideLength) { this.sideLength = sideLength; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int x = (getWidth() - (int) (sideLength * 10)) / 2; int y = (getHeight() - (int) (sideLength * 10)) / 2; int side = (int) (sideLength * 10); g.drawRect(x, y, side, side); } } class TrianglePanel extends JPanel { private double base; public TrianglePanel(double base) { this.base = base; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int[] xPoints = {getWidth() / 2, getWidth() / 2 - (int) (base * 10) / 2, getWidth() / 2 + (int) (base * 10) / 2}; int[] yPoints = {getHeight() / 2 - (int) (base * 10) / 2, getHeight() / 2 + (int) (base * 10) / 2, getHeight() / 2 + (int) (base * 10) / 2}; g.drawPolygon(xPoints, yPoints, 3); } } class RectanglePanel extends JPanel { private double width; private double height; public RectanglePanel(double width, double height) { this.width = width; this.height = height; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int x = (getWidth() - (int) (width * 10)) / 2; int y = (getHeight() - (int) (height * 10)) / 2; int rectWidth = (int) (width * 10); int rectHeight = (int) (height * 10); g.drawRect(x, y, rectWidth, rectHeight); } } class SpherePanel extends JPanel { private double radius; public SpherePanel(double radius) { this.radius = radius; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int circleRadius = (int) (radius * 10); // Scale up for better visualization g.drawOval(centerX - circleRadius, centerY - circleRadius, 2 * circleRadius, 2 * circleRadius); } } class CubePanel extends JPanel { private double sideLength; public CubePanel(double sideLength) { this.sideLength = sideLength; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int x = (getWidth() - (int) (sideLength * 10)) / 2; int y = (getHeight() - (int) (sideLength * 10)) / 2; int side = (int) (sideLength * 10); g.drawRect(x, y, side, side); } } class ConePanel extends JPanel { private double radius; private double height; public ConePanel(double radius, double height) { this.radius = radius; this.height = height; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int circleRadius = (int) (radius * 10); // Scale up for better visualization int x = centerX - circleRadius; int y = centerY - circleRadius; int width = 2 * circleRadius; int coneHeight = (int) (height * 10); g.drawArc(x, y, width, coneHeight, 0, 180); g.drawLine(centerX, centerY - circleRadius, centerX, centerY + coneHeight); } } class CylinderPanel extends JPanel { private double radius; private double height; public CylinderPanel(double radius, double height) { this.radius = radius; this.height = height; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int circleRadius = (int) (radius * 10); // Scale up for better visualization int x = centerX - circleRadius; int y = centerY - circleRadius; int width = 2 * circleRadius; int cylinderHeight = (int) (height * 10); // Draw top circle g.drawOval(x, y, width, width); // Draw bottom circle g.drawOval(x, y + cylinderHeight, width, width); // Draw connecting lines g.drawLine(centerX - circleRadius, centerY, centerX - circleRadius, centerY + cylinderHeight); g.drawLine(centerX + circleRadius, centerY, centerX + circleRadius, centerY + cylinderHeight); } } class TorusPanel extends JPanel { private double majorRadius; private double minorRadius; public TorusPanel(double majorRadius, double minorRadius) { this.majorRadius = majorRadius; this.minorRadius = minorRadius; setPreferredSize(new Dimension(200, 200)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int majorDiameter = (int) (2 * majorRadius * 10); int minorDiameter = (int) (2 * minorRadius * 10); g.drawOval(centerX - majorDiameter / 2, centerY - minorDiameter / 2, majorDiameter, minorDiameter); g.drawOval(centerX - majorDiameter / 2, centerY - majorDiameter / 2, majorDiameter, majorDiameter); } }
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |