Advertisement
DeveloperSergio

MySqL && JavaFX && PostgreSqL Part1

Dec 5th, 2016
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.55 KB | None | 0 0
  1. package login;
  2.  
  3. import javafx.application.Application;
  4. import javafx.collections.FXCollections;
  5. import javafx.collections.ObservableList;
  6. import javafx.event.ActionEvent;
  7. import javafx.event.EventHandler;
  8. import javafx.geometry.Insets;
  9. import javafx.geometry.Pos;
  10. import javafx.scene.Scene;
  11. import javafx.scene.control.*;
  12. import javafx.scene.image.Image;
  13. import javafx.scene.image.ImageView;
  14. import javafx.scene.layout.VBox;
  15. import javafx.stage.Stage;
  16.  
  17. import java.sql.*;
  18.  
  19.  
  20. public class Main extends Application {
  21.  
  22. // поля с настройками подключения к БД
  23. private static final String URL = "jdbc:postgresql://127.0.0.1:5432/testdb2";
  24. private static final String USER = "postgres";
  25. private static final String PASS = "root";
  26.  
  27. // поля для подключения
  28. private static Connection con;
  29. private static Statement stmt;
  30. private static ResultSet rs;
  31.  
  32. Label labelPicture = new Label();
  33.  
  34.  
  35.  
  36.  
  37. ComboBox<String> cbDataBases;
  38.  
  39. Label labelInfo = new Label();
  40.  
  41. TextField tfUrl = new TextField();
  42. TextField tfUser = new TextField();
  43. PasswordField tfPass = new PasswordField();
  44.  
  45. // кнопка вкл/выкл
  46. ToggleButton btnConn = new ToggleButton(" Connect ");
  47.  
  48.  
  49. // Query connectAndQuery = new Query();
  50. // класс подключения к БД
  51. ConnectDB connectDB = new ConnectDB();
  52. // класс отключения от БД
  53. Disconnect disconnect = new Disconnect();
  54.  
  55. public static void main(String[] args) {
  56. launch(args);
  57. }
  58.  
  59. public void start(Stage stage){
  60.  
  61.  
  62. stage.setTitle("Main menu");
  63.  
  64. // стиль кнопки из css
  65. // btnConn.setStyle("-fx-font: 16 arial; -fx-base: #2f9cd4;");
  66. btnConn.setId("btnConnColor");
  67.  
  68. // прозрачная подсказка в TestField
  69. tfUrl.setPromptText("jdbc:postgresql://");
  70. tfUser.setPromptText(" Enter username");
  71. tfPass.setPromptText(" Enter password");
  72.  
  73. // задаем размер TestField
  74. tfUrl.setPrefColumnCount(15);
  75. tfUser.setPrefColumnCount(15);
  76. tfPass.setPrefColumnCount(15);
  77.  
  78. // создать список типа Observablelist из элементов
  79. ObservableList<String> basesTypes = FXCollections.observableArrayList(" PostgreSqL",
  80. " MySqL");
  81.  
  82. // создаем комбинироаный список
  83. cbDataBases = new ComboBox<String>(basesTypes);
  84.  
  85. // корневой узел
  86. VBox root = new VBox();
  87. // отступ по краям VBox root
  88. root.setPadding(new Insets(0,0,15,0));
  89.  
  90.  
  91. // добавляем в Label картинку
  92. labelPicture.setGraphic( sizeLabelPicture("PostgreSqL") );
  93.  
  94. VBox vBoxTop = new VBox();
  95.  
  96. // отступы в vBoxTop
  97. vBoxTop.setPadding(new Insets(5,0,5,0));
  98.  
  99. // промежутки между элементами внутри vBoxTop
  100. vBoxTop.setSpacing(10);
  101. vBoxTop.setAlignment(Pos.CENTER);
  102.  
  103.  
  104.  
  105.  
  106. vBoxTop.getChildren().add(cbDataBases);
  107.  
  108. // добавляем imageViev в vBoxTop
  109. vBoxTop.getChildren().add(labelPicture);
  110.  
  111. VBox vBoxCenter = new VBox();
  112.  
  113. // промежутки между элементами внутри vBoxCenter
  114. vBoxCenter.setSpacing(5);
  115. // отступы вокруг vBoxCenter
  116. vBoxCenter.setPadding(new Insets(5, 20, 10, 20));
  117. // выравниваем все елементы по центру внутры vBoxCenter
  118. vBoxCenter.setAlignment(Pos.CENTER);
  119.  
  120. vBoxCenter.getChildren().addAll( tfUrl, tfUser, tfPass);
  121.  
  122.  
  123. // установить значение по умолчанию
  124. cbDataBases.setValue(" PostgreSqL");
  125.  
  126.  
  127. btnConn.setOnAction(new EventHandler<ActionEvent>() {
  128. @Override
  129. public void handle(ActionEvent ev) {
  130.  
  131.  
  132. // выбираем базу
  133. if ( (cbDataBases.getValue()).contains("PostgreSqL") &&
  134. (cbDataBases.getValue()).length() > 0 && btnConn.isSelected() ){
  135.  
  136. labelInfo.setText(" PostgreSqL Connected");
  137.  
  138.  
  139. // делаем не активной Combobox, TextField, делаем соответствующий текст и цвет button
  140. // подключаемся к базе
  141. activeInactive(true);
  142. }
  143. else if ( cbDataBases.getValue().contains("MySqL") && btnConn.isSelected() ) {
  144. labelInfo.setText(" Mysql Connected");
  145. // делаем не активной Combobox, TextField выводим соответствующий текст и цвет button
  146. // подключаемся к базе
  147. activeInactive(true);
  148.  
  149. }
  150. else if (cbDataBases.getValue().contains("MySqL") && !(btnConn.isSelected()) ){
  151. labelInfo.setText(" Mysql Disconnected");
  152. // делаем активной Combobox, TextField выводим соответствующий текст и цвет button
  153. // отключаемся от базы
  154. activeInactive(false);
  155. }
  156. else if (cbDataBases.getValue().contains("PostgreSqL") && !(btnConn.isSelected()) ){
  157.  
  158. labelInfo.setText(" PostgreSqL Disconnected");
  159.  
  160. // делаем активной Combobox, TextField выводим соответствующий текст и цвет button
  161. // отключаемся от базы
  162. activeInactive(false);
  163.  
  164. }
  165.  
  166.  
  167. }
  168. });
  169.  
  170. //слушатель и обработчик событий ComboBox
  171. cbDataBases.setOnAction(new EventHandler<ActionEvent>() {
  172. @Override
  173. public void handle(ActionEvent event) {
  174.  
  175. if (cbDataBases.getValue().contains( "MySqL") )
  176. labelPicture.setGraphic( sizeLabelPicture("MySqL") );
  177. else if (cbDataBases.getValue().contains( "PostgreSqL") )
  178. labelPicture.setGraphic( sizeLabelPicture("PostgreSqL") );
  179.  
  180.  
  181. }
  182. });
  183.  
  184. //сплывающая подсказка ComboBox
  185. cbDataBases.setTooltip( new Tooltip(" Select DataBase ") );
  186.  
  187. VBox vBoxButton= new VBox();
  188.  
  189.  
  190. // отступы вокруг vBoxCenter
  191. vBoxButton.setPadding(new Insets(10, 0, 0, 0));
  192.  
  193. // выравниваем элементы по ценру окна
  194. vBoxButton.setAlignment(Pos.CENTER);
  195.  
  196. vBoxButton.getChildren().add( btnConn);
  197.  
  198. // VBOX для LabelInfo
  199. VBox vBoxLabelInfo = new VBox();
  200.  
  201. vBoxLabelInfo.setPadding(new Insets(10, 0, 5, 0));
  202.  
  203. vBoxLabelInfo.getChildren().add(labelInfo);
  204.  
  205. vBoxLabelInfo.setAlignment(Pos.BOTTOM_CENTER);
  206.  
  207. // добавляем VBOX-root
  208. root.getChildren().addAll(vBoxTop,vBoxCenter, vBoxButton, vBoxLabelInfo);
  209.  
  210. // создаем сцену
  211. Scene scene = new Scene(root);
  212.  
  213. // сцена на подмостках
  214. stage.setScene(scene);
  215.  
  216. // отключем кнопку маximyze и фиксируем окно
  217. stage.setResizable(false);
  218.  
  219.  
  220. //по центру
  221. root.setAlignment(Pos.CENTER);
  222.  
  223. // добавляем стиль-css
  224. scene.getStylesheets().add(Main.class.getResource("MainWindow.css").toExternalForm());
  225.  
  226.  
  227. // показуем подмостку и сцену
  228. stage.show();
  229.  
  230.  
  231.  
  232.  
  233. }
  234.  
  235.  
  236. // метод задает размер иконки и отправляет в label
  237.  
  238. public ImageView sizeLabelPicture(String sqlType){
  239.  
  240. ImageView imageViewPic = new ImageView();
  241. if (sqlType.equals("PostgreSqL")){
  242. Image image = new Image(getClass().getResourceAsStream("postgreSql.png"));
  243.  
  244. imageViewPic.setFitHeight(55);
  245. imageViewPic.setFitWidth(55);
  246. imageViewPic.setImage(image);
  247. }
  248. else if (sqlType.equals("MySqL")){
  249. Image image = new Image(getClass().getResourceAsStream("mysql.png"));
  250. imageViewPic.setFitHeight(55);
  251. imageViewPic.setFitWidth(55);
  252. imageViewPic.setImage(image);
  253. }
  254.  
  255. return imageViewPic;
  256. }
  257.  
  258. // делаем активной/ неактивной Combobox, TextField
  259. public void activeInactive(boolean flag){
  260.  
  261. cbDataBases.setDisable(flag);
  262. tfUrl.setDisable(flag);
  263. tfUser.setDisable(flag);
  264. tfPass.setDisable(flag);
  265. if (flag == true){
  266. // получаем коннект и используем его для отключения
  267. con = connectDB.conDB(con, URL, USER, PASS);
  268. //подпись кнопки
  269. btnConn.setText("Disconnect");
  270.  
  271. // метка, стиль, цвет кнопки
  272. btnConn.setId("btnDisconColor");
  273.  
  274. // создаем метку для удачного подключения(зеленый цвет)
  275. labelInfo.setId("labelInfoConnColor");
  276. }
  277. else {
  278. // отключаемся от базы
  279. disconnect.disconMeth(con);
  280.  
  281. btnConn.setText(" Connect ");
  282. // создаем метку для отключения красный цвет)
  283. labelInfo.setId("labelInfoDisconColor");
  284.  
  285. // метка, стиль, цвет кнопки
  286. btnConn.setId("btnConnColor");
  287.  
  288. }
  289. }
  290.  
  291.  
  292. }
  293.  
  294.  
  295.  
  296. package login;
  297.  
  298. import java.sql.Connection;
  299. import java.sql.ResultSet;
  300. import java.sql.SQLException;
  301. import java.sql.Statement;
  302.  
  303. /**
  304. * Created by Admin on 03.12.2016.
  305. */
  306. public class Disconnect {
  307.  
  308. // поля для подключения
  309. // private static Connection con;
  310. // private static Statement stmt;
  311. // private static ResultSet rs;
  312.  
  313.  
  314. public void disconMeth(Connection con){
  315. //close connection ,stmt and resultset here
  316. if (con != null){
  317. try {con.close(); } catch(SQLException se) { /*can't do anything */ }
  318. }
  319.  
  320. // try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  321. // try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  322.  
  323.  
  324. }
  325.  
  326. }
  327.  
  328.  
  329. package login;
  330.  
  331. import java.sql.Connection;
  332. import java.sql.DriverManager;
  333. import java.sql.SQLException;
  334.  
  335. /**
  336. * Created by Admin on 02.12.2016.
  337. */
  338. public class ConnectDB {
  339. // поля с настройками подключения к БД
  340. // private static final String URL = "jdbc:postgresql://127.0.0.1:5432/testdb2";
  341. // private static final String USER = "postgres";
  342. // private static final String PASS = "root";
  343.  
  344. // Connection connection = null;
  345.  
  346. String resault = "";
  347.  
  348. public Connection conDB(Connection connection, String URL, String USER, String PASS){
  349. try {
  350. connection = DriverManager.getConnection(URL, USER, PASS);
  351.  
  352. } catch (SQLException e) {
  353. resault = "Connection Failed";
  354. e.printStackTrace();
  355. }
  356.  
  357. if (connection != null) {
  358. resault = "You successfully connected to database now";
  359. } else {
  360. resault = "Failed to make connection to database";
  361. }
  362.  
  363. return connection;
  364. }
  365.  
  366. }
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373. -------------------------------cssStyle-------------------------------------
  374.  
  375. .root {
  376. -fx-background-image: url("background12.png");
  377. }
  378. /*стиль для всплывающей подсказки*/
  379. .tooltip {
  380. -fx-background-color: linear-gradient(#e2ecfe, #99bcfd);
  381. }
  382. .page-corner {
  383. -fx-background-color: linear-gradient(from 0% 0% to 50% 50%,#3278fa,#99bcfd);
  384. }
  385.  
  386. .combo-box-base {
  387. -fx-font-family: "Arial Narrow";
  388. -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, white;
  389. -fx-background-insets: 0 0 -1 0, 0, 1, 2;
  390. -fx-background-radius: 3px, 3px, 2px, 1px;
  391. -fx-font-size: 12px;
  392. -fx-font-weight: bold;
  393. -fx-text-fill: #333333;
  394. -fx-effect: dropshadow( gaussian , rgba(255,255,255,0.5) , 0,0,0,1 );
  395. }
  396.  
  397.  
  398. #labelInfoDisconColor {
  399. -fx-font-size: 12px;
  400. -fx-font-weight: bold;
  401. -fx-text-fill: #e7241d;
  402. -fx-effect: dropshadow( gaussian , rgba(255,255,255,0.5) , 0,0,0,1 );
  403. }
  404.  
  405. #labelInfoConnColor {
  406. -fx-font-size: 12px;
  407. -fx-font-weight: bold;
  408. -fx-text-fill: #0ca374;
  409. -fx-effect: dropshadow( gaussian , rgba(255,255,255,0.5) , 0,0,0,1 );
  410. }
  411.  
  412. #btnConnColor{
  413. -fx-font: 16 arial;
  414. -fx-base: #2f9cd4;
  415. }
  416.  
  417. #btnDisconColor{
  418. -fx-font: 16 arial;
  419. -fx-base: #e7241d;
  420. }
  421. /*
  422.  
  423. .button {
  424. -fx-text-fill: white;
  425. -fx-font-family: "Arial Narrow";
  426. -fx-font-weight: bold;
  427. -fx-background-color: linear-gradient(#61a2b1, #2A5058);
  428. -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 );
  429. }
  430.  
  431. /* при наведении курсора на кнопку */ /*
  432. .button:hover {
  433. -fx-background-color: linear-gradient(#2A5058, #61a2b1);
  434. } */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement