Tástáil do scileanna Java - Sraith IV,,en,Scileanna Codála Java,,en,Déan do chuid eolais a thástáil,,en,Seo sraith eile leideanna Java,,en,Dhírigh muid go príomha ar an gcód códála agus feidhmithe,,en,Rinneamar plé a dhéanamh ar chur i bhfeidhm coiteann Java éagsúla le samplaí códaithe,,en,Is féidir leat é a thástáil go díreach trí do chód Java féin a chruthú,,en,Tá súil agam go gcabhróidh sé seo leat na rudaí bunúsacha i gcroílár Java a thuiscint,,en,Conas léirmhíniú infix a thiontú go léiriú iarchéime,,en,Sa sampla a leanas, léirítear conas an t-iontráil a thiontú go léiriú iar-iarratais trí choincheap an Stack a úsáid,,en,Brúigh anseo,,en,pop,,en,agus peek,,en,úsáidtear modhanna chun an tasc a dhéanamh,,en,Agus úsáidtear an rang Stack chun na habairtí a shealbhú,,en,rang phoiblí InToPost,,en,Stack theStack príobháideach,,en,ionchur String príobháideach,,en,aschur teorainneacha príobháideach;,,en,InToPost poiblí,,en,Teaghrán i,,en,ionchur = in,,en,int stackSize = input.length,,en,stackSize,,en

Java Coding Skills

Java Coding Skills – Test your knowledge

Réamhrá: This is another Java tips series. We have mainly focused on the coding and implementation part. We have discussed different common Java implementations with coding examples. You can test it directly by creating your own Java code. Hope this will help you understand the basic things in core Java.







How to convert an infix expression to postfix expression?

A: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.

java.io.IOException allmhairiú;

public class InToPost {

private Stack theStack;

private String input;

private String output = “”;

public InToPost(String in) {

input = in;

int stackSize = input.length();

theStack = new Stack(stackSize);

}

String doTrans poiblí,,en,input.length,,en,char ch = input.charAt,,en,ch,,en,cás ' ',,en,cás '-',,en,gotOper,,en,cás '*',,en,cás '/',,en,cás ',,en,gotParen,,eu,aschur = aschur,,en,theStack.pop,,en,aschur fillte,,en,neamhoifig phoiblí gotOper,,en,char opThis,,en,réamh prec1,,en,char opTop = theStack.pop,,en,onTop == ',,nl,Ar Barr,,nl,réamh prec2,,en,atTop == ' ,,nl,atTop == '-',,nl,prec2 =,,en,prec2,,en,prec1,,en,seo,,en,neamhní poiblí gotParen,,en,char ch,,en,char chx = theStack.pop,,en,chx == ',,en,chx,,en,Ionchur teorainneacha;,,en,Aschur teorainn,,en,InToPost theTrans = InToPost nua,,en,aschur = theTrans.doTrans,,en,Is é Postfix,,en,charra príobháideach,,en,Stack eagar,,sv,int max,,en,maxSize = max,,en,stackArray = char nua,,en,maxSize,,en,barr,,en,brúigh neamhní poiblí,,en,char j,,en,barr,,en,= j,,en,pop poiblí char,,en,filleadh ar StackArray,,en,bualadh poiblí poiblí,,en,boolean poiblí isEmpty,,en,barr ==,,en,Tabharfaidh an sampla cód thuas an toradh seo a leanas,,en,Conas an Ceue a chur i bhfeidhm,,en() {

le haghaidh (int j = 0; j < input.length(); j ) {

char ch = input.charAt(j);

switch (ch) {

case ‘ ’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(&#8216;:

theStack.push(ch);

break;

case ‘)’:

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

cé (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

public void gotOper(char opThis, int prec1) {

cé (!theStack.isEmpty()) {

char opTop = theStack.pop();

más rud é go (opTop == ‘(&#8216;) {

theStack.push(opTop);

break;

}

else {

int prec2;

más rud é go (opTop == ‘ ’ || opTop == ‘-‘)

prec2 = 1;

else

prec2 = 2;

más rud é go (prec2 < prec1)

{

theStack.push(opTop);

break;

} else

output = output + opTop;

}

}

theStack.push(opThis);

}

public void gotParen(char ch){

cé (!theStack.isEmpty()) {

char chx = theStack.pop();

más rud é go (chx == ‘(&#8216;)

break;

else

output = output + chx;

}

}

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) throws IOException {

String input = “1+2*4/5-7+3/6”;

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + output + ‘n’);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

The above code sample will produce the following result.

124*5/+7-36/+

Postfix is 124*5/+7-36/+

How to implement Queue?

A: Sa sampla a leanas, léiríonn sé conas scuaine a chur i bhfeidhm i struchtúr fostaithe,,en,Is é an liosta nasctha ná cur i bhfeidhm an chomhéadain Liosta,,en,Cuireann sé gach oibríocht liosta roghnach ar fáil,,en,agus ceadann sé gach gné,,en,áirítear null,,en,Chomh maith le comhéadan an Liosta a chur i bhfeidhm. Soláthraíonn an rang LinkedList modhanna ainmnithe go haonfhoirmeach,,en,gné a bhaint agus a chur isteach ag tús agus ag deireadh an liosta,,en,Ceadaíonn na hoibríochtaí seo liostaí nasctha le húsáid mar stack,,en,scuaine,,en,nó scuaine dúbailte,,en,allmhairiú java.util.LinkedList,,en,GenQueue ranga,,en,liosta príobháideach LinkedList = LinkedList nua,,en,neamhní poiblí,,en,E mír,,en,list.addLast,,en,poiblí E dequeue,,en,ar ais list.poll,,en,Tá,,en,list.isEmpty,,en,méid an phobail,,en,list.size ar ais,,en,breiseáin neamhní poiblí,,en,GenQueue q,,en,q.hasanna,,en,q.dequeue,,en,rang poiblí GenQueueTest,,en,GenQueue empList,,fr,empList = GenQueue nua,,fr,GenQueue hList,,en,hList = GenQueue nua,,en. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(item);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

cé (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue,,en,Fostaí nua in aghaidh na huaire,,en,empList.addItems,,en,hList,,en,Na fostaithe,,en,ainmneacha iad,,en,empList.hasItems,,fr,Employee emp = empList.dequeue,,fr,emp.firstName,,en,emp.lastName,,en,`Teaghrán poiblí lastName,,en,String first public,,en,Teaghrán deiridh,,en,String first,,en,this.lastName = deireanach,,en,this.firstName = an chéad,,en,String to public,,en,ar ais firstName,,en,Síneann an Fostaire gach Uair ar an bhFostaí,,en,poiblí gach uair in aghaidh na huaire,,en,Poiblí in aghaidh na huaire Fostaí,,en,deireanach,,en,T D,,en,G B,,en,F S,,en,Conas sreang a athrú trí úsáid a bhaint as stack,,en,Taispeánann sampla a leanas conas an téadán a athrú trí úsáid a bhaint as stack le cabhair ó StringReverserThroughStack modh sainithe an úsáideora,,en,Stack simplí i Java,,en,curtha i bhfeidhm mar chuspóir-dhírithe,,en,struchtúr athchúrsach sonraí,,en,liosta nasctha singil,,en,Tabhair faoi deara go dtugann Java rang Stack cheana féin,,en,rang poiblí StringReverserThroughStack,,en,aschur teaghrán príobháideach,,en,poiblí StringReverserThroughStack,,en,String doRev poiblí,,en,Stack theStack = Stack nua,,en(new HourlyEmployee(“T”, “D”));

hList.enqueue,,en,Fostaí nua in aghaidh na huaire,,en,empList.addItems,,en,hList,,en,Na fostaithe,,en,ainmneacha iad,,en,empList.hasItems,,fr,Employee emp = empList.dequeue,,fr,emp.firstName,,en,emp.lastName,,en,`Teaghrán poiblí lastName,,en,String first public,,en,Teaghrán deiridh,,en,String first,,en,this.lastName = deireanach,,en,this.firstName = an chéad,,en,String to public,,en,ar ais firstName,,en,Síneann an Fostaire gach Uair ar an bhFostaí,,en,poiblí gach uair in aghaidh na huaire,,en,Poiblí in aghaidh na huaire Fostaí,,en,deireanach,,en,T D,,en,G B,,en,F S,,en,Conas sreang a athrú trí úsáid a bhaint as stack,,en,Taispeánann sampla a leanas conas an téadán a athrú trí úsáid a bhaint as stack le cabhair ó StringReverserThroughStack modh sainithe an úsáideora,,en,Stack simplí i Java,,en,curtha i bhfeidhm mar chuspóir-dhírithe,,en,struchtúr athchúrsach sonraí,,en,liosta nasctha singil,,en,Tabhair faoi deara go dtugann Java rang Stack cheana féin,,en,rang poiblí StringReverserThroughStack,,en,aschur teaghrán príobháideach,,en,poiblí StringReverserThroughStack,,en,String doRev poiblí,,en,Stack theStack = Stack nua,,en(new HourlyEmployee(“G”, “B”));

hList.enqueue,,en,Fostaí nua in aghaidh na huaire,,en,empList.addItems,,en,hList,,en,Na fostaithe,,en,ainmneacha iad,,en,empList.hasItems,,fr,Employee emp = empList.dequeue,,fr,emp.firstName,,en,emp.lastName,,en,`Teaghrán poiblí lastName,,en,String first public,,en,Teaghrán deiridh,,en,String first,,en,this.lastName = deireanach,,en,this.firstName = an chéad,,en,String to public,,en,ar ais firstName,,en,Síneann an Fostaire gach Uair ar an bhFostaí,,en,poiblí gach uair in aghaidh na huaire,,en,Poiblí in aghaidh na huaire Fostaí,,en,deireanach,,en,T D,,en,G B,,en,F S,,en,Conas sreang a athrú trí úsáid a bhaint as stack,,en,Taispeánann sampla a leanas conas an téadán a athrú trí úsáid a bhaint as stack le cabhair ó StringReverserThroughStack modh sainithe an úsáideora,,en,Stack simplí i Java,,en,curtha i bhfeidhm mar chuspóir-dhírithe,,en,struchtúr athchúrsach sonraí,,en,liosta nasctha singil,,en,Tabhair faoi deara go dtugann Java rang Stack cheana féin,,en,rang poiblí StringReverserThroughStack,,en,aschur teaghrán príobháideach,,en,poiblí StringReverserThroughStack,,en,String doRev poiblí,,en,Stack theStack = Stack nua,,en(new HourlyEmployee(“F”, “S”));

empList.addItems(hList);

System.out.println(“The employees’ names are:”);

cé (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + ” ” + emp.lastName);

}

}

}

class Employee {

` public String lastName;

public String firstName;

public Employee() {

}

public Employee(String last, String first) {

this.lastName = last;

this.firstName = first;

}

public String toString() {

return firstName + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

Super(last, first);

}

}

The above code sample will produce the following result.

The employees’ names are:

T D

G B

F S

How to reverse a string using stack?

A: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class

java.io.IOException allmhairiú;

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

le haghaidh (slánuimhir i = 0; i < input.length(); i ) {

char ch = input.charAt(i);

theStack.push(ch);

}

aschur;,,en,char ch = theStack.pop,,en,Foinse agus Tacaíocht Java,,en,StringReverserThroughStack theReverser =,,en,StringReverserThroughStack nua,,en,aschur = theReverser.doRev,,en,Reversed,,en,JavaStringReversal,,nl,lasreveRgnirtSavaJ,,no,Conas a sheiceáil cibé an bhfuil cumas antialiasing nó nach bhfuil,,en,Sa sampla a leanas, léirítear conas a sheiceáil an bhfuil an t-aistriú ag iompú ar Rang RenderingHints nó nach bhfuil ag baint úsáide as,,en,Tarlaíonn ailíniú nuair a bhíonn comhartha ann,,en,comhartha grafaicí 2D,,en,a sampláil agus a chainníochtú ó spás leanúnach i spás sainithe,,en,Is é an sampláil an próiseas maidir le luach a léamh ó chomhartha atá ag athrú go leanúnach,,en,Is é an próiseas cainníochtú trína ndéantar luach ar leithligh a shannadh ar na luachanna samplála leanúnach sa spás críochnaithe a léiríonn digiteach,,en,dénártha-bhunaithe,,en,allmhairiú java.awt.Graphics,,en,allmhairiú java.awt.Graphics2D,,en,allmhairiú java.awt.RenderingHints,,en,allmhairiú javax.swing.JComponent,,en “”;

cé (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) throws IOException {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

System.out.println(“Reversed: ” + output);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

 

}

}

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ







How to check whether antialiasing is enabled or not?

A: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) systems.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

allmhairiú javax.swing.JFrame;

public class Main {

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) {

Fráma JFrame = Fráma nua,,en,frame.add,,en,MyComponent nua,,en,frame.setSize,,en,fráma,,en,síneann MyComponent rang JComponent,,en,péint neamhní poiblí,,en,Grafaicí g,,en,Graphics2D g2 =,,en,Graphics2D,,en,RenderingHints rh = g2d.getRenderingHints,,de,boolean bl = rh.containsValue,,en,RenderingHints.VALUE_ANTIALIAS_ON,,en,le,,mt,g2.setRenderingHint,,ku,RenderingHints,,en,PRÍOMHLÁTHAÍOCHTA,,en,Bréagach,,en,Conas dathanna a thaispeáint i bhfráma,,en,Tar éis sampla taispeánann sé conas a léiríonn na dathanna go léir i bhfráma le modh setRGB de rang íomhá,,en,Is é an Íomhá ranga teibí an t-ollchineál de na ranganna go léir a léiríonn íomhánna grafacha,,en,Ní mór an íomhá a fháil ar bhealach ard-shonrach,,en,allmhairiú java.awt.event.WindowAdapter,,en,allmhairiú java.awt.event.WindowEvent,,en,allmhairiú java.awt.image.BufferedImage,,en,An rang poiblí Leathnaíonn Príomh-Chomhfhreagras J,,en,Íomhá BufferedImage,,en,leithead,,en,int airde = getSize,,en,sonraí = nua int,,en,innéacs int =,,en();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(fíor);

}

}

class MyComponent extends JComponent {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

The above code sample will produce the following result.

False

False

False

How to display colors in a frame?

A: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

allmhairiú javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

int[] data = new int[width * height];

int index = 0;

le haghaidh (slánuimhir i = 0; i < height; i ) {

int dearg,,en,int uaine;,,en,gorm,,en,innéacs ,,en,gorm,,en,íomhá = BufferedImage nua,,en,BufferedImage.TYPE_INT_RGB,,en,image.setRGB,,en,íomhá == null,,en,tosaithe,,en,g.drawImage,,en,íomha,,en,JFrame f = Fráma nua,,en,Dathanna Taispeáin,,en,f.getContentPane,,en,Main nua,,en,f.setSize,,en,f.setLocation,,en,f.addWindowListener,,en,WindowAdapter nua,,en,Fuinneog neamhní poiblí,,en,Fuinneog e,,en,f.setVisible,,en,Taispeánann na dathanna go léir i bhfráma,,en,Cad atá ag snáithiú i java,,en,Is féidir go leor snáitheanna a bheith i gclár Java,,en,is féidir iad uile a chruthú gan eolas soiléir ar an bhforbróir,,en,is gá duit a mheas nuair a scríobhann tú iarratas Java,,en,tá snáithe tosaigh ann a thosaíonn a oibriú trí na príomhghníomhartha a chur i bhfeidhm,,en,modh d'iarratais,,en,Nuair a scríobhann tú feidhmchláirín Java,,en,tá snáithe ann a bhíonn ag feidhmiú na modhanna aisghabhála,,en,tús,,en,actionPerformed,,en,de do feidhmchláirín,,en (i * 255) / (height – 1);

le haghaidh (int j = 0; j < width; j ) {

int green = (j * 255) / (width – 1);

int blue = 128;

data[index ] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

más rud é go (image == null)

initialize();

g.drawImage(image, 0, 0, this);

}

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) {

JFrame f = new JFrame(“Display Colours”);

f.getContentPane().cuir(new Main());

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(fíor);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.








What is threading in java?

A: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), etc.) of your applet; déanaimid labhairt ar an snáithe seo mar snáithe an fhearais,,en,I gceachtar cás,,en,Tosaíonn do chlár leis an méid is féidir leat a mheas mar snáithe amháin,,en,Más mian leat I / O a dhéanamh,,en,go háirithe má d'fhéadfadh an I / O bloc,,en,tús lasc ama,,en,nó aon tasc eile a dhéanamh i gcomhthreo leis an snáithe tosaigh,,en,ní mór duit snáithe nua a thosú chun an tasc sin a dhéanamh,,en,Conas téacs a thaispeáint i gclónna éagsúla,,en,Taispeánann an sampla a leanas conas an téacs a thaispeáint i gclónna éagsúla ag baint úsáide as setFont,,en,modh d'aicme Cló,,en,Léiríonn an t-aicme Font clónna,,en,a úsáidtear chun téacs a chur ar fáil ar bhealach infheicthe,,en,Soláthraíonn cló an fhaisnéis atá riachtanach chun seicheálacha carachtair a mhapáil ar shraitheanna de glyphs agus seicheálacha glyphs a thabhairt ar rudaí Grafacha agus Comhpháirt,,en,allmhairiú java.awt.event. *,,en,Rang poiblí Leathnaíonn Príomh-JPanel,,en,Serif,,en,SansSerif,,en,stíleanna;,,en,Font.PLAIN,,en. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.

How to display text in different fonts?

A: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.

java.awt allmhairiú. *;

import java.awt.event.*

allmhairiú javax.swing. *

public class Main extends JPanel {

Teaghrán[] type = { “Serif”,”SansSerif”};

int[] styles = { Font.PLAIN, Cló .ITALIC,,en,Font.BOLD,,en,stylenames;,,nl,Plain,,en,Iodáilis,,en,Trom,,en,int f =,,en,cineál.leithead,,en,f ,,en,int s =,,en,stíleanna,,en,s ,,en,Clóigh cló = Cló nua,,en,stíleanna,,en,g.setFont,,en,cló,,en,Ainm teaghrán = cineál,,en,mban stíl,,nl,g.drawString,,en,f.setContentPane,,en,Taispeántar cló-ainmneacha éagsúla i bhfráma,,en,Conas líne a tharraingt ag baint úsáide as GUI,,en,Tar éis sampla a léiríonn conas líne a tharraingt ag baint úsáide as tarraingt,,en,modh rang Graphics2D le réad Line2D mar argóint,,en,An setPaint,,en,úsáidtear modh an ranga Graphics2D chun an líne a phéinteáil,,en,Seo feidhmchláirín java a úsáidtear chun an líne a thaispeáint ar JFrame,,en,allmhairiú java.awt.geom.Line2D,,en,allmhairiú javax.swing.JApplet,,en,Rang poiblí Leathnaíonn Príomh-JApplet,,en,tionscnamh neamhní poiblí,,en,setForeground,,en,RenderingHints.KEY_ANTIALIASING,,en,g2.setPaint,,en,Dath.gray,,en,int x =,,en,int y =,,es,g2.draw,,en,Líne2D nua,,en,g2.drawString,,en,Líne,,en,String s,,en,JApplet applet = Main Main,,en,Ionad,,en,feidhmchláirín,,en,applet.init,,en,f.pack,,en,Taispeántar an líne i bhfráma,,en, Font.BOLD,

Cló .ITALIC,,en,Font.BOLD,,en,stylenames;,,nl,Plain,,en,Iodáilis,,en,Trom,,en,int f =,,en,cineál.leithead,,en,f ,,en,int s =,,en,stíleanna,,en,s ,,en,Clóigh cló = Cló nua,,en,stíleanna,,en,g.setFont,,en,cló,,en,Ainm teaghrán = cineál,,en,mban stíl,,nl,g.drawString,,en,f.setContentPane,,en,Taispeántar cló-ainmneacha éagsúla i bhfráma,,en,Conas líne a tharraingt ag baint úsáide as GUI,,en,Tar éis sampla a léiríonn conas líne a tharraingt ag baint úsáide as tarraingt,,en,modh rang Graphics2D le réad Line2D mar argóint,,en,An setPaint,,en,úsáidtear modh an ranga Graphics2D chun an líne a phéinteáil,,en,Seo feidhmchláirín java a úsáidtear chun an líne a thaispeáint ar JFrame,,en,allmhairiú java.awt.geom.Line2D,,en,allmhairiú javax.swing.JApplet,,en,Rang poiblí Leathnaíonn Príomh-JApplet,,en,tionscnamh neamhní poiblí,,en,setForeground,,en,RenderingHints.KEY_ANTIALIASING,,en,g2.setPaint,,en,Dath.gray,,en,int x =,,en,int y =,,es,g2.draw,,en,Líne2D nua,,en,g2.drawString,,en,Líne,,en,String s,,en,JApplet applet = Main Main,,en,Ionad,,en,feidhmchláirín,,en,applet.init,,en,f.pack,,en,Taispeántar an líne i bhfráma,,en + Font.BOLD };

Teaghrán[] stylenames =

{ “Plain”, “Italic”, “Bold”, “Bold & Italic” };

public void paint(Graphics g) {

le haghaidh (int f = 0; f < type.length; f ) {

le haghaidh (int s = 0; s < styles.length; s ) {

Font font = new Font(type[f], styles[s], 18);

g.setFont(font);

String name = type[f] + ” ” + stylenames[s];

g.drawString(ainm, 20, (f * 4 + s + 1) * 20);

}

}

}

statach neamhní príomh phoiblí(Teaghrán[] a) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(fíor);

}

}

The above code sample will produce the following result.

Different font names are displayed in a frame.

How to draw a line using GUI?

A: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.

java.awt allmhairiú. *;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

allmhairiú javax.swing.JFrame;

public class Main extends JApplet {

public void init() {

setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString(“Line”, x, 250);

}

statach neamhní príomh phoiblí(String s[]) {

JFrame f = new JFrame(“Line”);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().cuir(“Center”, applet);

applet.init();

f.pack();

f.setSize(Toise nua(300, 300));

f.setVisible(fíor);

}

}

The above code sample will produce the following result.

Line is displayed in a frame.

Conas teachtaireacht a thaispeáint i bhfráma nua,,en,Taispeánann sampla mar seo conas teachtaireacht a thaispeáint i bhfráma nua trí fhráma a chruthú ag baint úsáide as JFrame,,en,ag baint úsáide as JFrames getContentPanel,,en,Modhanna chun é seo a thaispeáint ar an bhfráma,,en,Seo a leanas na ranganna Graphics2D agus Rectangle2D an comhábhar tosaigh a dhéanamh,,en,Agus ansin taispeántar an teachtaireacht ar chomhpháirt JPanel,,en,allmhairiú java.awt.font.FontRenderContext,,en,allmhairiú javax.swing.JPanel,,en,g2.setFont,,en,Cló nua,,en,péintHorizontallyCenteredText,,hi,g2,,en,Foinse Java,,en,neamhní cosanta paintHorizontallyCenteredText,,en,Graphics2D g2,,en,snámhphointe centerX,,en,bonnlíne snámhphointe,,en,FontRenderContext frc = g2.getFontRenderContext,,en,Teorainneacha Rectangle2D = g2.getFont,,en,getStringBounds,,en,frc,,en,leithead snámhphointe;,,en,bounds.getWidth,,en,centerX,,en,bunlíne,,en,Taispeánann JAVA agus J2EE i bhFráma nua,,en,Conas píosa cairt a thaispeáint ag baint úsáide as fráma,,en?

A: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component. And then the message is displayed on a JPanel component.

java.awt allmhairiú. *;

import java.awt.font.FontRenderContext;

méid java.awt.geom.Rectangle2D;

allmhairiú javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font(“Serif”, Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);

paintHorizontallyCenteredText(g2, “agus”, 200, 125);

paintHorizontallyCenteredText(g2, “Support”, 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

float width = (float) bounds.getWidth();

g2.drawString(s, centerX – width / 2, baselineY);

}

statach neamhní príomh phoiblí(Teaghrán[] comhbhrí leis an rogha) {

JFrame f = new JFrame();

f.getContentPane().cuir(new Main());

f.setSize(450, 350);

f.setVisible(fíor);

}

}

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.







How to display a pie chart using a frame?

A: Taispeánann sampla mar a léirítear piechart trí rang Slices a dhéanamh,,en,ag cruthú stua ag brath ar na slices,,en,Sa sampla seo úsáidtear AWT agus comhpháirteanna swing chun an chairt a tharraingt,,en,Déantar argóintí chuig an drawPie,,en,modh ón bpríomhoide,,en,Agus taispeántar an chairt comhlánaithe ar JFrame,,en,allmhairiú java.awt.Rectangle,,en,Slice ranga,,en,luach dúbailte,,en,Dath dath,,en,Slice poiblí,,en,seo.value = luach,,en,seo.color = dath,,en,Slice,,en,slisní,,en,Slice nua,,en,Color.black,,en,Dath.green,,en,Color.red,,en,MyComponent,,en,drawPie,,pl,getBounds,,en,slisní,,en,drawPie neamhní,,en,Graphics2D g,,en,Ceantar dronuilleog,,en,iomlán dúbailte = 0.0D,,en,slices.length,,en,iomlán = slices,,en,curValue dúbailte = 0.0D,,en,tús tosaigh =,,en,startAngle =,,sv,curValue,,en,int arcAngle;,,en,g.setColor,,en,g.fillArc,,en,area.x,,en,area.y,,en,area.width,,en,area.height,,en,uillinn ag tosú,,sv,arcAngle,,es,curValue = slices,,en,frame.getContentPane,,en,Taispeáin piechart ar fhráma,,en & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () modh. And the completed chart is displayed on a JFrame.

allmhairiú java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

allmhairiú javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

le haghaidh (slánuimhir i = 0; i < slices.length; i ) {

total = slices[i].luach;

}

double curValue = 0.0D;

int startAngle = 0;

le haghaidh (slánuimhir i = 0; i < slices.length; i ) {

startAngle = (int) (curValue * 360 / total);

int arcAngle = (int) (slices[i].luach * 360 / total);

g.setColor(slices[i].color);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue = slices[i].luach;

}

}

}

public class Main {

statach neamhní príomh phoiblí(Teaghrán[] argv) {

Fráma JFrame = Fráma nua,,en,frame.add,,en,MyComponent nua,,en,frame.setSize,,en,fráma,,en,síneann MyComponent rang JComponent,,en,péint neamhní poiblí,,en,Grafaicí g,,en,Graphics2D g2 =,,en,Graphics2D,,en,RenderingHints rh = g2d.getRenderingHints,,de,boolean bl = rh.containsValue,,en,RenderingHints.VALUE_ANTIALIAS_ON,,en,le,,mt,g2.setRenderingHint,,ku,RenderingHints,,en,PRÍOMHLÁTHAÍOCHTA,,en,Bréagach,,en,Conas dathanna a thaispeáint i bhfráma,,en,Tar éis sampla taispeánann sé conas a léiríonn na dathanna go léir i bhfráma le modh setRGB de rang íomhá,,en,Is é an Íomhá ranga teibí an t-ollchineál de na ranganna go léir a léiríonn íomhánna grafacha,,en,Ní mór an íomhá a fháil ar bhealach ard-shonrach,,en,allmhairiú java.awt.event.WindowAdapter,,en,allmhairiú java.awt.event.WindowEvent,,en,allmhairiú java.awt.image.BufferedImage,,en,An rang poiblí Leathnaíonn Príomh-Chomhfhreagras J,,en,Íomhá BufferedImage,,en,leithead,,en,int airde = getSize,,en,sonraí = nua int,,en,innéacs int =,,en();

frame.getContentPane().cuir(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(fíor);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share