- Какие существуют библиотеки для создания графических интерфейсов на Java
- JavaFX
- Swing
- SWT
- Graphics Class in Java
- How does Graphic Class work in Java?
- 1. drawRoundRect (int a1, int b1, int width, int height, int horArc, int vertArc )
- 2. public abstract void fillRoundRect (int x,int y,int width,int height, int arcWidth,int arcHeight)
- 3. public abstract void clipRect (int x, . int y, int width, int height)
- 4. public void fill3DRect(int a1,int b1, int width,int height,boolean leveled)
- 5. public abstract void drawOval (int a,int b,int width1,int height1)
- 6. public abstract void setColor (Color)
- 7. public abstract void drawLine (int a1, int b1, int a2, int b2)
- Examples of Graphics Class in Java
- Example #1
- Example #2
- Conclusion
- Recommended Articles
Какие существуют библиотеки для создания графических интерфейсов на Java
Узнайте о популярных библиотеках JavaFX, Swing и SWT для создания графических интерфейсов в Java-приложениях!
Java предлагает множество библиотек для создания графических интерфейсов. В этой статье мы рассмотрим популярные библиотеки, которые используются разработчиками для создания визуальных компонентов в Java-приложениях. 😃
JavaFX
JavaFX является современной библиотекой для создания графических интерфейсов в Java-приложениях. Она предоставляет множество встроенных компонентов, таких как кнопки, текстовые поля, таблицы и слайдеры. Также поддерживает CSS-стилизацию.
Пример создания простого окна с кнопкой в JavaFX:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class Main extends Application < public static void main(String[] args) < launch(args); >@Override public void start(Stage primaryStage) < Button btn = new Button("Click me!"); StackPane root = new StackPane(btn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("JavaFX Example"); primaryStage.setScene(scene); primaryStage.show(); >>
Swing
Swing — это более старая библиотека, чем JavaFX, но до сих пор используется в некоторых проектах. Swing предоставляет широкий набор компонентов и возможностей для создания графических интерфейсов. Однако, Swing имеет менее современный дизайн и не поддерживает CSS.
Пример создания простого окна с кнопкой в Swing:
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Main < public static void main(String[] args) < JFrame frame = new JFrame("Swing Example"); JButton button = new JButton("Click me!"); JPanel panel = new JPanel(); panel.add(button); frame.add(panel); frame.setSize(300, 250); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); >>
SWT
Standard Widget Toolkit (SWT) — это библиотека для создания графических интерфейсов, разработанная компанией IBM. SWT предоставляет набор стандартных виджетов, таких как кнопки, текстовые поля и таблицы. SWT использует нативные компоненты операционной системы, что обеспечивает высокую производительность и совместимость с различными платформами.
Пример создания простого окна с кнопкой в SWT:
import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Main < public static void main(String[] args) < Display display = new Display(); Shell shell = new Shell(display); Button button = new Button(shell, SWT.PUSH); button.setText("Click me!"); button.setBounds(10, 10, 100, 30); shell.setSize(300, 250); shell.open(); while (!shell.isDisposed()) < if (!display.readAndDispatch()) < display.sleep(); >> display.dispose(); > >
Выбор библиотеки для создания графических интерфейсов зависит от ваших потребностей и опыта. JavaFX является наиболее современным и рекомендуется для новых проектов, однако Swing и SWT могут быть подходящими для определенных ситуаций или для работы с существующими проектами.
Помимо этих, существуют и другие сторонние библиотеки, но в данной статье мы остановились на наиболее популярных и широко используемых. Удачи вам в изучении Java-разработки! 🚀
Graphics Class in Java
It is an abstract class present in java.awt package that extends the Object class of java.lang package that serves as a superclass for all graphics contexts, which allow drawing various components in an application that can be easily realized onto various devices or many real images.
Web development, programming languages, Software testing & others
Every single object of the Graphics class is a complete package of all the methods needed for the implementation of basic functions of an applet, and with this, its state contains information related to the component on which to draw, current clip, current color, XOR alternation color, font or translations of origin.
Syntax with Parameters
public abstract class Graphics extends Object
Graphics class is an abstract class; thus, we cannot make its objects; instead, we need to use one of its subclasses such as DebugGraphics, Graphics2D. And it is also a public class; it can be accessed using any of the class.
It extends the Object class in java.lang package thus extends all its functions such as clone, equals, etc.
How does Graphic Class work in Java?
Graphics class is used to draw different visualized components on the screen that is considered as a drawing board composed of the infinite number of pixels that lie between the pixels of the output device. All the coordinates that are given as arguments to the function are considered relative to the origin that has been translated before triggering the method. Below is the procedure when we give different points in any of the methods:-
- While drawing an outline of a figure, an infinitely thin path is traversed between the pixels and placed a pixel-sized pen at the bottom and right of the anchor points.
- While drawing a given rectangle, one extra row at the right and bottom edges are occupied, whereas while filling it, the same boundaries are used to fill the color that has been set using the setColor method.
- If one writes a text, the text is written above the base coordinates.
- While drawing a baseline for a text, the pixels right below the text are considered to draw the line.
All the operations that can be performed modify the pixels lying within the Shape specified and are controlled using an object of Graphics class. This region is referred to as the user clip that can only be modified using setClip and clipReact methods.
A device clip specifying the main clipping region combined with the above-described user clip defines a composite clip that defines the region for final clipping. All drawings or writings are done in the current color, in the current font, and using the current paint mode.
1. drawRoundRect (int a1, int b1, int width, int height, int horArc, int vertArc )
This function is used to create a rectangle with rounded corners where
a1 – This argument denotes the x coordinate of the rectangle’s top-left corner to be drawn.
b1 – This argument denotes the y coordinate of the rectangle’s top-left corner to be drawn.
width – This argument denotes the width of the rectangle to be drawn.
height – This argument denotes the height of the rectangle to be drawn.
horArc – This argument denotes the horizontal diameter of the arc for all the corners of the rectangle to be drawn.
vertArc – This argument denotes the vertical diameter of the arc for all the corners of the rectangle to be drawn.
The left edge = x and right edge = x+width -1
Top edge = y and bottom edge = y+height -1
2. public abstract void fillRoundRect (int x,int y,int width,int height, int arcWidth,int arcHeight)
This method is used to fill rounded corner rectangle with the color specified as the current color. Parameters interpretation is the same as given in the drawRoundRect() method.
3. public abstract void clipRect (int x, . int y, int width, int height)
This method is used to intersect the current clip with the specifications of the rectangle. In case the current clip area is null, the specified rectangle is set as the new clip that can be modified using setClip methods. These operations do not affect the outside of the clipping area.
4. public void fill3DRect(int a1,int b1, int width,int height,boolean leveled)
This method is used to paint a 3-D highlighted rectangle filled with the color specified using the setColor method. To give a 3D look to the figure, edges will be beveled to some extent and highlighted from the top left corner.
a1 –This argument denotes the x coordinate of the rectangle’s top-left corner to be drawn.
b1 -This argument denotes the y coordinate of the rectangle’s top-left corner to be drawn.
width – This argument denotes the width of the rectangle to be drawn.
height – This argument denotes the height of the rectangle to be drawn.
leveled – a boolean value, if it Is true – rectangle made will be shown as leveled above the surface; otherwise, it will be shown on the same level of the surface.
5. public abstract void drawOval (int a,int b,int width1,int height1)
This method is used to draw the empty oval in the boundaries of the rectangle whose dimensions have been specified. The area of this oval extends upto width+1 pixels and height+1 pixels.
a –This argument denotes the x coordinate of the top left corner of the oval.
b – This argument denotes the y coordinate of the top left corner of the oval.
width1 –This argument denotes the width of the oval.
height1 –This argument denotes the height of the oval.
6. public abstract void setColor (Color)
This method is used to set the current color for the graphics object. It takes the final variable as the value of color from the Color class in java.awt package. All the operations following this line will use this particular color.
7. public abstract void drawLine (int a1, int b1, int a2, int b2)
This method is used to draw a line, using the current color, between the points (a1, b1) and (a2, b2) in this graphics context’s coordinate system.
a1 –x coordinate of the starting point of the line.
b1 – y coordinate of the starting point of the line
a2 – x coordinate of the ending point of the line.
b2 – y coordinate of the ending point of the line.
Examples of Graphics Class in Java
Different examples are mentioned below:
Example #1
Let’s draw a simple applet in java
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class Demo extends Frame < public Demo()< prepareWindow(); >@Override public void paint(Graphics g) < g.setColor(Color.GRAY); Font currentFont = new Font("Berlin Sans FB Demi",Font.ITALIC, 24); g.setFont(currentFont); g.setColor(Color.BLUE); g.drawString("Welcome to Graphics Class", 100, 150); g.setColor(Color.GREEN); g.drawLine(100, 200, 400, 200); >public static void main(String[] args) < Demo awtGraphicsDemo = new Demo(); awtGraphicsDemo.setVisible(true); >private void prepareWindow() < setSize(450,400); addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); > >
Example #2
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class Demo extends Frame < public Demo()< super("Java AWT Examples"); prepareWindow(); >public static void main(String[] args) < Demo awtGraphicsDemo = new Demo(); awtGraphicsDemo.setVisible(true); >private void prepareWindow() < setSize(450,400); addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); > @Override public void paint(Graphics g) < g.setColor(Color.GRAY); Font currentFont = new Font("Berlin Sans FB Demi", Font.ITALIC, 24); g.setFont(currentFont); g.drawString("Welcome to Graphics Class", 100, 150); g.setColor(Color.magenta); g.drawRoundRect(150, 400, 100, 150, 20, 20); g.setColor(Color.CYAN); g.fillRoundRect(400, 400, 150, 120, 20,10); Font newFont1 = new Font("ALGERIAN", Font.ITALIC, 30); g.setFont(newFont1); g.setColor(Color.orange); g.fill3DRect(600, 400, 500, 120, false); g.setColor(Color.blue); g.drawString("Welcome to Graphics Class", 1000, 700); g.drawOval(600,200,400,100); g.drawLine(100, 170, 500, 170); >>
Conclusion
Graphics class provides all the basic operations required to create the visualizing objects on the screen and all information related to its state or font properties and modifying them. However, since it’s an abstract class thus, its instance cannot be created directly, thus called using its subclasses.
Recommended Articles
This is a guide to Graphics Class in Java. Here we discuss How does Graphic Classwork in Java along with the examples, syntax and, parameters. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8