import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.Shape;import java.awt.geom.Ellipse2D;
import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.SwingUtilities;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;
public class RoundedJButton extends JButton {
/** * */ private static final long serialVersionUID = 1L;
public RoundedJButton(String title) { super(title); Dimension size = getPreferredSize(); size.width = size.height = Math.max(size.width, size.height); setPreferredSize(size);
setContentAreaFilled(false); }
@Override protected void paintComponent(Graphics g) { if (getModel().isArmed()) { g.setColor(Color.lightGray); } else { g.setColor(getBackground()); } g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
super.paintComponent(g); }
@Override protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawOval(0, 0, getSize().width - 1, getSize().height - 1); }
Shape shape;
@Override public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight()); } return shape.contains(x, y); }
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
JFrame frame = new JFrame(); frame.setTitle("It's all about Java..."); frame.setSize(150, 150); GridLayout layout = new GridLayout(); layout.setRows(1); layout.setHgap(10); layout.setVgap(10); frame.setLayout(layout);
JTextField field1 = new JTextField(); field1.setText("This is a textfield!"); frame.getContentPane().add(field1);
RoundedJButton button = new RoundedJButton("Browse"); button.setBackground(Color.gray); button.setForeground(Color.GREEN); frame.getContentPane().add(button);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { frame.pack(); frame.setVisible(true); } }); }}
Wednesday, 6 January 2021
Java - Swing custom components - Rounded JButton
Tuesday, 15 September 2020
Coding and best practices
Write code or write code in right way...
Writing a coding solution to a problem can be done in many ways. If the solution can be obtained with less number of code lines, then it is easy to understand and maintain.
But what if code is large with having millions of lines. Moreover maintenance and readability becomes difficult as the code base grows... Right?
Aspects to consider while coding:
- Naming convention
- Cyclomatic Complexity
- SOLID principles
- DRY Principle
- Managing dead code
- Comments
Naming conventions:
Every programming language mandates few norms in order to name variables, classes and functions etc. For ex: Java uses class names first letter to be a alphabet and rest to be lower case letters.
But if we dig little bit more, naming conventions are not limited to only upper case or lower case letters and using alphanumeric letters etc.
Naming a variable must be enough concise as naming your first child's name...
Few bad names for variables and constants:
int final static MAX_LENGHT = 2; [Correct]
Cyclomatic Complexity:
Cyclomatic complexity is a measure or metric to estimate complexity level of a snippet or block of code.
Cyclomatic complexity and best practices:
- Never put more than three conditional checks (&& operator and || operator etc.) in one if condition
- Never exceed more than thirty lines in one function or method.
- Never exceed more than 1000 lines in one class or one file.
SOLID principles:
Usually developing a large and scalable application, requires better design. Adhering to SOLID principles yields better scalable and easily maintainable applications.
There are five SOLID principles. They are:
- Single Responsibility Principle
- Open/Closed Principle
- Liskov's Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
DRY Principle:
DRY stands for Do Not Repeat Yourself. Sometimes, There could be a need to use same or similar set of lines of code to be used multiple times in the same application. For ex. String utilities, DB connections or updating records in database etc.
Writing frequently used code snippets multiple times is not a good practice. Instead move this code to a function or method and use this method in places where ever required.
Simple use cases are:
- DB Connections
- File IO Operations
- String Utilities etc.
Managing Dead Code:
Sometimes there are some lines or instructions in code base, which are completely not executed in all cases at all. This is considered as dead code.
Dead code reduces the quality with respect to the readability.
Comments:
Comments increases the readability of the program for programmers. Comments are written at class level, method level and variable level [Constants, instance variables and class variables] differently.The reason for this difference is, the pattern of comments is identified by API document generator tools and generates API documents.
Conclusion:
Sunday, 9 August 2020
Exception handling and java keywords
Exception:
Exception in a programming language and in English language is pretty similar. Exception means being different from or not following the rules. And in programming language like Java, exception is an event which occurs during the execution of a program that disturbs the complete flow of application or program.
When something beyond expected happens while executing a program is considered as an error. handling these errors or abnormality is called as Exception handling.
Exception Handling:
Exception handling in java is managed with the help of java keywords and java API support..
1. Java Keywords
2. Java API support
Java Keywords:
There are 5 keywords in Java.
1. Try
2. catch
3. finally
4. throw
and 5. throws
These five keywords used all together or combination of few keywords are used on need basis.
1. Try:
The code or set of instructions which are prone to errors or exceptions are enclosed in try block.
For example dividing a five or some number with zero [5/0]. The result of 5/0 is undefined and in Java, this scenario is considered as exception.
2. Catch:
Usually try block is followed by a catch block. If some exception is occurred in try block, the execution control is moved to catch block instead of continuing the execution of try block's code.
The purpose of catch block is, handling the exceptions that are raised in try.
There is a possibility of handling multiple scenarios in multiple catches.
NOTE: Multiple catches can be written for single try.
Java code example:
try{
--- // code
} catch(OtherException e) {
--- // code
}catch(AnotherException e) {
}
3. Finally:
Usually if there is an exception in try block, the rest of the lines in try are not executed and control moves on to catch block. And if there is no exception at all in try block control never moves to catch block. Then catch block is considered to be dead code.
Then where must we write mandatory code?
So, finally block is written after try and catch which gets executed always.
Java code example:
try{
---
} catch (Exception e) {
---
} finally{
--- // mandatory code for execution
}
NOTE: Always put mandatory code in finally block. For example: closing IO resources connections like network and database connections etc
4. Throws and Throw:
Throws and throw keywords works along with Java API support. I will explain the Java API support for Exception handling in next subsequent articles.
For now, we can understand that for every exception scenario there is one Java class(Java API). Example: Number divided by zero. [5/0]. The result is ArithmeticException
Java code example:
try{
int result = 5/0;
--- // other code
}catch(ArithmeticException e) {
--- // exception of try block is handled here
}
Why there is no "throws" keyword here....?
The alternative solution for above snippet with throws and throw for checking election voting age eligibility exception is:
void votingAgeNumber() throws ArithmeticException{
int age = 12;
if(age <=18) {
throw new ArithmeticException("Age is not sufficient to vote");
}
--- // other code
}
NOTE: Sometimes "throws" keyword works as an alternative solution for try and catch blocks. The throws keyword is used instead of try and catch.
Example:
Solution with throws:
void divideNumber() throws ArithmeticException{
int result = 5/0;
}
And snippet with try and catch:
void divideNumber(){
try{
int result = 5/0;
}catch(ArithmeticException e){
---- // handle exception
}
} // method end
The above both solutions are same, but with different keywords.
Some key points:
1. There can be one try with multiple catch blocks.
2. Try block can be followed by either catch or finally block.
3. Or both can be followed
4. Throws is like warning that exception can be thrown and throw keyword is real accident took place.
I wrote here https://www.allabtjava.com/2021/01/java-api-support-for-exception-handling.html on checked exceptions and runtime or unchecked exceptions.
Happy coding... :)
Popular posts
-
Swing toolkit comes with few standard Layout Managers where none of them serves the need of arranging components in a way that usually deve...
-
After understanding and using swing toolkit, I understood that there is a allot of scope to develop Custom components easily. I have deve...
-
Swing toolkit provides a component called JColorChooser to choose colors. It allows users to select color from multiple color combination...
-
This post is intended to beginners of java swing toolkit programmers. It is a simple java program which demonstrates the swing based File ...
-
Evolution of Java: First of all, The Java programming language and it's tools that we currenly using is not what actually expected. This...
-
If you are interested in designing GUIs and building custom components with Swing toolkit, definitely Romain guy's blog can be good ref...
-
JavaFX provides different layout panes for arranging components on them. for example GridPane, BorderPane etc. This article describes abou...
-
NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...
-
Software development activities can be managed and taken care with different life cycle models. These life cycle models has became legacy si...
-
IDE: Integrated Development Environment Integrated development environment, in short IDE is a convenient environment to write, execute and ...
Demonstration of Java NullPointerException
NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...