Приложение 1. Аплети с геометрични фигури.
// A Java applet displaying a white circle in a black square
import java.awt.*;
import javax.swing.*;
public class CircleInSquare extends JApplet
{
public void paint(Graphics graphics)
{
final int X = 50, Y = 50, SIZE = 50;
graphics.setColor(Color.BLACK);
graphics.fillRect(X, Y, SIZE, SIZE);
graphics.setColor(Color.WHITE);
graphics.fillOval(X, Y, SIZE, SIZE);
}}
Модифицирайте програмата за да получите горните фигури.
Приложение 2. Калкулатор. Програма, която може да се стартира и като аплет и като приложение.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleCalc extends JApplet{
public static void main(String[] args) {
JFrame window=new JFrame("simple calculator");
CalcPanel content=new CalcPanel();//object of nested class defined below
window.setContentPane(content);
window.pack(); // Sizes window to preferred size of contents.
window.setLocation(100,100);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
public void init() {
setContentPane( new CalcPanel() );
}
public static class CalcPanel extends JPanel implements ActionListener {
private JTextField xInput, yInput; // Input boxes for the numbers.
private JLabel answer; // JLabel for displaying the answer, or an
// error message if appropriate.
public CalcPanel() {
//Задаване цвета на фона,който се вижда между компонентите
setBackground(Color.GRAY);
// Добавяне на гранична рамка около панела
setBorder( BorderFactory.createEmptyBorder(5,5,5,5) );
// Създаване на входните кутии в бял цвят (по подразбиране също са бели)
xInput = new JTextField("0", 10);
xInput.setBackground(Color.WHITE);
yInput = new JTextField("0", 10);
yInput.setBackground(Color.WHITE);
//Създаване на панели, които съдържат входните кутии и етикети "x =" и "y = ". //Тези панели са подредени от арганизатор по подразбиране FlowLayout
JPanel xPanel = new JPanel();
xPanel.add( new JLabel(" x = "));
xPanel.add(xInput);
JPanel yPanel = new JPanel();
yPanel.add( new JLabel(" y = "));
yPanel.add(yInput);
//Създаване на панела,съдържаща 4 бутона за 4-те аритметични операции. Използва //се организатор GridLayout така че бутоните да са с еднакви размери
//Главната панела buttonPanel служи като слушател за бутоните ActionListener.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,4));
JButton plus = new JButton("+");
plus.addActionListener(this);
buttonPanel.add(plus);
JButton minus = new JButton("-");
minus.addActionListener(this);
buttonPanel.add(minus);
JButton times = new JButton("*");
times.addActionListener(this);
buttonPanel.add(times);
JButton divide = new JButton("/");
divide.addActionListener(this);
buttonPanel.add(divide);
//Създаване на етикет за изписване на резултата, който е в червено на бял
//фон. Етикетът се задава прозрачен ("opaque") за да сме сигурни че няма да //засенчи фона.
answer = new JLabel("x + y = 0", JLabel.CENTER);
answer.setForeground(Color.red);
answer.setBackground(Color.white);
answer.setOpaque(true);
//Задаваме организатор на главната панела от вида GridLayout и добавяме всички //компоненти, които сме създали
setLayout(new GridLayout(4,1,3,3));
add(xPanel);
add(yPanel);
add(buttonPanel);
add(answer);
//Даваме “фокуса” на кутията xInput, което е естествено място за стартиране
xInput.requestFocus();
} // end constructor
/*Когато ползователя натисне даден бутон вземете числата от входните кутии и изпълнете операцията зададета от бутона. Поставете резултата в етикета answer. Ако възникне грешка в етикета се появява съобщение за това.*/
public void actionPerformed(ActionEvent evt) {
double x, y; // The numbers from the input boxes.
/* Вземете число от текстовото поле xInput. Използвайте метода
xInput.getText() за да превърнете съдържанието в низ (String). Превърнете низа в число от тип double. Конструкцията try...catch ще провери за грешки в низа. Ако низа не е легално число се появява съобщението "Illegal data for x." и метода actionPerformed() завършва. */
try {
String xStr = xInput.getText();
x = Double.parseDouble(xStr);
}
catch (NumberFormatException e) {
// The string xStr is not a legal number.
answer.setText("Illegal data for x.");
xInput.requestFocus();
return;
}
/* По същия начин получаваме число от текстовото поле yInput */
try {
String yStr = yInput.getText();
y = Double.parseDouble(yStr);
}
catch (NumberFormatException e) {
answer.setText("Illegal data for y.");
yInput.requestFocus();
return;
}
/*Извършваме операцията според надписа на бутона. Забележете че деленето на нула предизвиква съобщение за грешка. */
String op = evt.getActionCommand();
if (op.equals("+"))
answer.setText( "x + y = " + (x+y) );
else if (op.equals("-"))
answer.setText( "x - y = " + (x-y) );
else if (op.equals("*"))
answer.setText( "x * y = " + (x*y) );
else if (op.equals("/")) {
if (y == 0)
answer.setText("Can't divide by zero!");
else
answer.setText( "x / y = " + (x/y) );
}
} // end actionPerformed()
} // end nested class CalcPanel
} // end class SimpleCalculator
Сподели с приятели: |