Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Пример использования SWT в JAVA 
:(
    Опции темы
AntonSaburov
Дата 26.1.2005, 15:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Штурман
****


Профиль
Группа: Модератор
Сообщений: 5658
Регистрация: 2.7.2002
Где: Санкт-Петербург

Репутация: 51
Всего: 118



Данный пример сделан для демонстрации использования SWT из пакета Eclipse.
Данное приложение решает обычное квадратное уравнение. Все пожелания принимаются автором с огромным вниманием.

Код

package swt_package;

import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;

// Roots incapsulation class.
class QuadraticRoots {    
    // Equation roots variables.
    private double x1 = 0, x2 = 0;
    // Solution present flag.
    private boolean solutionIsPresent = false;
    
    // Constructor for valid results.    
    public QuadraticRoots(double x1, double x2) {
  super();
  this.x1 = x1;
  this.x2 = x2;
  this.solutionIsPresent = true;
    }
    
    // Constructor for invalid results.    
    public QuadraticRoots() {
  super();
    }
    
    //Methods.    
    public double getX1() { 
  return x1; 
    }
  
    public double getX2() { 
  return x2; 
    }
  
    public boolean isSolutionPresent() { 
  return solutionIsPresent;
    }
}

// Window drawing and reaction class.
class ShowQuadraticInterface {
    
    private final Shell shell;
    private final Text aValue;
    private final Text bValue;
    private final Text cValue;
    private final Label x1Result;
    private final Label x2Result;
    
    public ShowQuadraticInterface() {  
  Display display = new Display();
  this.shell = new Shell(
      display, (SWT.BORDER | SWT.CLOSE | SWT.TITLE));
  this.shell.setText("Quadratic equation solution project. Copyright VPh.");
            
  // Create Table.
  this.shell.setLayout(new GridLayout(2, true));
        
  // Output controls.   
  createInvintationLabel("Please, enter A,B,C-coefficients of the equation: A*x^2 + B*x + C = 0");
  this.aValue = createUserEntryControl("Please, enter 'A' value:", "1");
  this.bValue = createUserEntryControl("Please, enter 'B' value:", "3");
  this.cValue = createUserEntryControl("Please, enter 'C' value:", "1");
     
  // Output solution button.
  Button buttonToSolve =  createSolveButton("Solve current Quadratic equation");
  // Create button click method.
  buttonToSolve.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
    ShowQuadraticInterface.this.performCalculation();
      }
  });
        
  // Output results controls.
  this.x1Result = createResultLabel();
  this.x2Result = createResultLabel();
        
  // Open window.
  this.shell.pack();
  this.shell.open();
 
  // Waiting window close.
  while (!shell.isDisposed()) {
    if (!display.readAndDispatch()) {
      display.sleep();
    }
  }
  display.dispose();
    }
    
    // Methods.
    private Label createInvintationLabel(String labelText) {    
  GridData userHintGrid = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
  userHintGrid.horizontalSpan = 2;  
  Label userHint = new Label(this.shell, SWT.NONE);
  userHint.setLayoutData(userHintGrid);
  userHint.setText(labelText);
  return userHint;  
    }
    
    private Text createUserEntryControl(
  String labelText,
  String initialText) {
    
  new Label(this.shell, SWT.NONE).setText(labelText);
  GridData vData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
  vData.horizontalSpan = 1;
  Text res = new Text(this.shell, SWT.SINGLE | SWT.BORDER);
  res.setLayoutData(vData);
  res.setText(initialText);
  return res;    
    }
  
    private Label createResultLabel() {
  Label result = new Label(this.shell, SWT.NONE);
  GridData lData = new GridData(GridData.FILL_HORIZONTAL);
  result.setLayoutData(lData);
  return result; 
    }    
    
    private Button createSolveButton(String buttonText) {    
     Button buttonToSolve = new Button(this.shell, SWT.CENTER);
  GridData buttonGrid = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
  buttonGrid.horizontalSpan = 2; 
     buttonToSolve.setLayoutData(buttonGrid);
     buttonToSolve.setText(buttonText);
     return buttonToSolve;
    }
    
    private void drawResults(QuadraticRoots roots) {      
  if (roots.isSolutionPresent()) {
      this.x1Result.setText("x1 = " + String.valueOf(roots.getX1()));
      this.x2Result.setText("x2 = " + String.valueOf(roots.getX2()));
     } else {
      this.x1Result.setText("No real roots.");
     }
    }
    
    private void clearResults() {
  this.x1Result.setText("");
  this.x2Result.setText("");
    }
    
    //Quadratic solution method.
    public QuadraticRoots quadraticSolve(double a, double b, double c) {   
   
   double discriminant = b*b - 4*a*c;      
  
   if (discriminant < 0)
    return new QuadraticRoots();
  
   double x1Root = 0, x2Root = 0;
   if (discriminant > 0) {
    x1Root = (-b + Math.sqrt(discriminant)) / 2*a;
    x2Root = (-b - Math.sqrt(discriminant)) / 2*a;
   } else // == 0
    x1Root = x2Root = -b / 2*a;
     
   return new QuadraticRoots(x1Root, x2Root);
  }    
  
    private void performCalculation() {  
  clearResults();
  //Quadratic equation coefficients.
  double a = 0, b = 0, c = 0;        
  try {
      a = new Double(aValue.getText()).doubleValue();
      b = new Double(bValue.getText()).doubleValue();
      c = new Double(cValue.getText()).doubleValue();
  } catch (NumberFormatException exp) {
      // Input error throw.
      this.x1Result.setText("Input Error: " + exp.getLocalizedMessage());
      return;
  }
  //Create solution class for good coefficients.
  drawResults(quadraticSolve(a,b,c));          
    }      
}

// Start up application.
public class swt_class {// SWTQuadraticEquationSolverDemo {
    
    public static void main(String[] args) {
  ShowQuadraticInterface inputInterface = new ShowQuadraticInterface();
  System.out.println("Bye-bye :-)");
    }    
    
    
    
}



А вот еще один вариант, который предоставил NotGonnaGetUs

Код

package swt_package;

class QuadraticRoots { // Roots incapsulation class.
    public static final QuadraticRoots ANY_SOLUTION = new QuadraticRoots(Double.NaN);
    public static final QuadraticRoots NO_SOLUTION = new QuadraticRoots(Double.NaN);

    private double x1, x2; // Equation roots variables.

    public QuadraticRoots(double x) { // Constructor for valid results.
        this(x, x);
    }

    public QuadraticRoots(double x1, double x2) { // Constructor for valid results.
        this.x1 = x1;
        this.x2 = x2;
    }

    public double getX1() { return x1; }

    public double getX2() { return x2;  }

    public boolean isAny() {
        return this == ANY_SOLUTION;
    }

    public boolean isNotExist() {
        return this == NO_SOLUTION;
    }

    public boolean isExist() {
        return !Double.isNaN(x1) && !Double.isNaN(x2);
    }

    public static QuadraticRoots getSolution(double a, double b, double c) { //get roots of  ax^2 + bx + c = 0;

        if (a == 0 && b == 0) { //solve  c = 0;
            if (c != 0) {
                return NO_SOLUTION;
            } else {
                return ANY_SOLUTION;
            }
        }

        if (a == 0) { //solve bx + c = 0;
            return new QuadraticRoots(-c / b);
        }

        double discriminant = b * b - 4 * a * c;

        if (discriminant < 0) {
            return NO_SOLUTION;
        }

        double x1, x2;
        if (discriminant == 0) {
            x1 = x2 = -b / (2 * a);
        } else { // discriminant > 0
            double d = Math.sqrt(discriminant);
            x1 = (-b + d) / (2 * a);
            x2 = (-b - d) / (2 * a);
        }
        return new QuadraticRoots(x1, x2);
    }
}

class ShowQuadraticInterface { // Window drawing and reaction class.

    private final Shell shell;
    private final Text aValue;
    private final Text bValue;
    private final Text cValue;
    private final Label x1Result;
    private final Label x2Result;

    public ShowQuadraticInterface() {
        Display display = new Display();
        shell = new Shell(display, (SWT.BORDER | SWT.CLOSE | SWT.TITLE));
        shell.setText("Quadratic equation solution project. Copyright VPh.");
        shell.setLayout(new GridLayout(2, true)); //Create Table.

        GuiBuilder builder = new GuiBuilder(shell);

        // Output controls.
        builder.createInvintationLabel("Please, enter A,B,C-coefficients of the equation: A*x^2 + B*x + C = 0");
        aValue = builder.createUserEntryControl("Please, enter 'A' value:", "1");
        bValue = builder.createUserEntryControl("Please, enter 'B' value:", "3");
        cValue = builder.createUserEntryControl("Please, enter 'C' value:", "1");

        // Output solution button.
        builder.createSolveButton("Solve current Quadratic equation").addSelectionListener(new SelectionAdapter() { // Create button click method.
            public void widgetSelected(SelectionEvent e) {
                performCalculation();
            }
        });

        // Output results controls.
        x1Result = builder.createResultLabel();
        x2Result = builder.createResultLabel();

        // Open window.
        shell.pack();
        shell.open();

        // Waiting window close.
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }


    private void performCalculation() {
        clearResults();
        //Quadratic equation coefficients.
        double a, b, c;
        try {
            a = new Double(aValue.getText()).doubleValue();
            b = new Double(bValue.getText()).doubleValue();
            c = new Double(cValue.getText()).doubleValue();
        } catch (NumberFormatException exp) {
            // Input error throw.
            x1Result.setText("Input Error: " + exp.getLocalizedMessage());
            return;
        }
        //Create solution class for good coefficients.
        drawResults(QuadraticRoots.getSolution(a, b, c));
    }

    private void drawResults(QuadraticRoots roots) {
        if (roots.isNotExist()) {
            x1Result.setText("No real roots.");
        } else if (roots.isAny()) {
            x1Result.setText("x1 = any value");
            x2Result.setText("x2 = any value");
        } else {
            x1Result.setText("x1 = " + String.valueOf(roots.getX1()));
            x2Result.setText("x2 = " + String.valueOf(roots.getX2()));
        }
    }

    private void clearResults() {
        this.x1Result.setText("");
        this.x2Result.setText("");
    }


    private static class GuiBuilder {
        private Shell shell;

        GuiBuilder(Shell shell) {
            this.shell = shell;
        }

        Label createInvintationLabel(String labelText) {
            GridData userHintGrid = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
            userHintGrid.horizontalSpan = 2;
            Label userHint = new Label(shell, SWT.NONE);
            userHint.setLayoutData(userHintGrid);
            userHint.setText(labelText);
            return userHint;
        }

        Text createUserEntryControl(String labelText,
                                    String initialText) {
            new Label(this.shell, SWT.NONE).setText(labelText);
            GridData vData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
            vData.horizontalSpan = 1;
            Text res = new Text(shell, SWT.SINGLE | SWT.BORDER);
            res.setLayoutData(vData);
            res.setText(initialText);
            return res;
        }

        Label createResultLabel() {
            Label result = new Label(shell, SWT.NONE);
            result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            return result;
        }

        Button createSolveButton(String buttonText) {
            Button buttonToSolve = new Button(shell, SWT.CENTER);
            GridData buttonGrid = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
            buttonGrid.horizontalSpan = 2;
            buttonToSolve.setLayoutData(buttonGrid);
            buttonToSolve.setText(buttonText);
            return buttonToSolve;
        }

    }
}


// Start up application.

public class aaa {// SWTQuadraticEquationSolverDemo {

    public static void main(String[] args) {
        ShowQuadraticInterface inputInterface = new ShowQuadraticInterface();
        System.out.println("Bye-bye :-)");
    }


}


PM MAIL WWW ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0456 ]   [ Использовано запросов: 23 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.