DB-GUI und JButton

airliner

Erfahrenes Mitglied
Tach Leute!

Bin jetzt in der vierten JAVA-Woche und komm noch nicht so ganz mit dem ActionListener und den Streams zurecht.

Im Praktikum habe ich die Aufgabe ein kleines Prog zu schreiben, welches verbindung zur DB herstellt und dort auch ausliest bzw Tabellen manipuliert.

Die verbindung klappt auch, nur hab ich jetzt Probleme mit meiner GUI.

Ich hab eine jComboBox, woe sämtliche Tabellen aufgelistet sind, die in der DB für meinen Account dort einsehbar sind. rechts daneben befindet sich ein TextField, wo man die SQL-Befehle eingeben soll. Hier wäre es wünschenswert, wenn der String aus der ComboBox (sprich der name der Tabelle der DB) in das TextField übernommen werden kann.
Es steht dabei von vornherein "SELECT * FROM " drin und DAHINTER soll der Tabellenname stehen, nachdem er markiert wurde.

So, das ist das Eine.

Das andere ist, dass ich zwei Buttons hab. Einer zum Verbinden bzw Trennen der Verbindung zur DB (wie gesagt, die verbindung an sich t auch, nur noch nicht auf Button-Click), und der Andere ist dazu da, um die SQL-Befehle auszuführen (das könnte komplizierter werden als ich es mir derzeit ausmale oder?)

Und dann will ich es noch hinkriegen, dass sowohl Ergebnisse der Abfrage der DB, als auch eventl Fehlermeldungen in der zusätzlichen jTextArea ausgegeben werden (befindet sich noch unter den Butten).

Wenn ihr es mit Eclipse oder ähnlichem kompiliert, werdet ihr ja die GUI sehen und vllt auch wissen, was ich meine.


Hier der Code:
Code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
import javax.swing.event.*;

/**
  *
  * @Beschreibung: Kleine einfache GUI zum Verbinden mit der Pumacy Oracle-Test-DB,
  * Daten auslesen und verändern mittels SQL-Befehle
  *
  * @version 1.0 vom 22.09.2008
  * @author: Florian Adler
  */

public class Datenbank_auslesen extends JFrame {
  // Anfang Attribute
  private String[] jComboBox1Data = {};
  private JComboBox jComboBox1 = new JComboBox(jComboBox1Data);
  private JTextField jTextField1 = new JTextField();
  private JButton jButton1 = new JButton();
  private JLabel jLabel1 = new JLabel();
  private JLabel jLabel2 = new JLabel();
  private JTextArea jTextArea1 = new JTextArea("");
  private JButton jButton2 = new JButton();

  
  
  
  
   // Ende Attribute

  public Datenbank_auslesen(String title) {
    // Frame-Initialisierung
    super(title);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    int frameWidth = 500;
    int frameHeight = 500;
    setSize(frameWidth, frameHeight);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - getSize().width) / 2;
    int y = (d.height - getSize().height) / 2;
    setLocation(x, y);
    Container cp = getContentPane();
    cp.setLayout(null);
    // Anfang Komponenten
    Font f= new Font("ComicSans", Font.BOLD, 12);
    jComboBox1.setFont(f);
    jComboBox1.setBounds(24, 48, 210, 24);
    jComboBox1.setBackground(Color.WHITE);
    jComboBox1.setForeground(Color.BLACK);
    jComboBox1.addItem("-------------");
    jComboBox1.addItem(" 0-9 ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" A ... ");
    jComboBox1.addItem("Action");
    jComboBox1.addItem("Action2Systemrole");
    jComboBox1.addItem("AuthenticationInstrument");
    jComboBox1.addItem("AuthenticationMethod");
    jComboBox1.addItem("AuthenticationMethod2Channel");
    jComboBox1.addItem("Author2Document");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" B ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" C ...");
    jComboBox1.addItem("Category");
    jComboBox1.addItem("Category Keyword");
    jComboBox1.addItem("Change Request");
    jComboBox1.addItem("Channel");
    jComboBox1.addItem("Commentaries");
    jComboBox1.addItem("Community");
    jComboBox1.addItem("CommunityTemplates");
    jComboBox1.addItem("CommunityUser");
    jComboBox1.addItem("CommunityUsergroup");
    jComboBox1.addItem("ComminutyWorkflow");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" D ...");
    jComboBox1.addItem("Document");
    jComboBox1.addItem("DocumentArchive");
    jComboBox1.addItem("DocumentField");
    jComboBox1.addItem("DocumentFieldArchive");
    jComboBox1.addItem("DocumentHistory");
    jComboBox1.addItem("DocumentParticipants");
    jComboBox1.addItem("DocumentRating");
    jComboBox1.addItem("DocumentSignature");
    jComboBox1.addItem("DocumentTypeCategory");
    jComboBox1.addItem("DocumentTypeSequence");
    jComboBox1.addItem("Document2Category");
    jComboBox1.addItem("Document2Document");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" E ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" F ...");
    jComboBox1.addItem("Favorites");
    jComboBox1.addItem("FQSFDocument");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" G ...");
    jComboBox1.addItem("Group2WFRole");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" H ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" I ...");
    jComboBox1.addItem("IntendedReleasePeriodDate");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" J ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" K ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" L ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" M ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" N ...");
    jComboBox1.addItem("News");
    jComboBox1.addItem("Notification");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" O ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" P ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" Q ...");
    jComboBox1.addItem("QSFDocument");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" R ...");
    jComboBox1.addItem("RatingItem");
    jComboBox1.addItem("RatingType");
    jComboBox1.addItem("ReviewReleaseDate");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" S ...");
    jComboBox1.addItem("Systemrole");
    jComboBox1.addItem("Systemuser");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" T ...");
    jComboBox1.addItem("Template");
    jComboBox1.addItem("TemplateCategory");
    jComboBox1.addItem("TemplateField");
    jComboBox1.addItem("TemplateWorkflow");
    jComboBox1.addItem("TimeForInitialTraining");
    jComboBox1.addItem("TrainingParicipant");
    jComboBox1.addItem("TrainingSession");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" U ...");
    jComboBox1.addItem("Usergroup");
    jComboBox1.addItem("User2Systemrole");
    jComboBox1.addItem("User2Usergroup");
    jComboBox1.addItem("User2WFRole");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" V ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" W ...");
    jComboBox1.addItem("WFRole");
    jComboBox1.addItem("WFRole2WFStatus");
    jComboBox1.addItem("WFRole2WFTrans");
    jComboBox1.addItem("WFStatus");
    jComboBox1.addItem("WFStatusphases");
    jComboBox1.addItem("WFStatus Properties");
    jComboBox1.addItem("WFTransition");
    jComboBox1.addItem("WFTransitionConditions");
    jComboBox1.addItem("WFTransitionConstraints");
    jComboBox1.addItem("WFTransitionFinalizers");
    jComboBox1.addItem("WFTransitionProperties");
    jComboBox1.addItem("WFWorkflow");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" X ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" Y ...");
    jComboBox1.addItem("-----------------------------------------------");
    jComboBox1.addItem(" Z ...");
    cp.add(jComboBox1);
    
    jTextField1.setBounds(250, 48, 233, 80);
    jTextField1.setText("SELECT * FROM "  );
    cp.add(jTextField1);
    
    jButton1.setBounds(288, 152, 150, 41);
    jButton1.setText("Ausführen");
    cp.add(jButton1);
    
    
    jLabel1.setBounds(24, 24, 114, 16);
    jLabel1.setText("Tabelle auswählen");
    jLabel1.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
    cp.add(jLabel1);
    
    jLabel2.setBounds(232, 24, 131, 16);
    jLabel2.setText("SQL-Befehl eingeben:");
    jLabel2.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
    cp.add(jLabel2);
    
    jTextArea1.setText("");
    jTextArea1.setBounds(16, 232, 433, 201);
    jTextArea1.setEditable(false);
    cp.add(jTextArea1);
    
    jButton2.setBounds(40, 152, 150, 41);
    jButton2.setText("Verbinden/Trennen");
    cp.add(jButton2);
    

           
        	
    // Ende Komponenten

    setResizable(false);
    setVisible(true);
  
   
  }


  public static void main(String[] args) {
    new Datenbank_auslesen("Oracle-Test-Datenbank-Zugriff");
    Connection con = null;
        Statement stmt = null;
        ResultSet result = null;
        String db_Url = "jdbc:oracle:thin:@kmmaster-ts:1521:XE";
        String db_UserName = "xxxx";
        String db_UserPw = "zzzz";
        
        
        

        
        
    try {
          Class.forName("oracle.jdbc.driver.OracleDriver");
          }catch (Exception e) {
                System.out.println("Treiber konnte nicht gefunden werden "+e);
                }
     try{
         con = DriverManager.getConnection(db_Url, db_UserName, db_UserPw);
      }catch(Exception e) {
       e.printStackTrace();
      }
      finally{

          if(null != result) {
              try{result.close();} catch(Exception ex) {}
           }

           if(null != stmt) {
              try{stmt.close();} catch(Exception ex) {}
           }

           if(null != con) {
              try{con.close();} catch(Exception ex) {}
           }
      }
      
      
  }
}

Wenn ihr Vorschläge habt, bitte möglichst mit Beispielcode (ich verändere diese auch gerne, ihr sollt also nicht meinen Code vervollständigen, sondern damit nur Denkanstöße geben. Immerhin will ich ja die Sprache lernen)


Was mich außerdem interessieren würde (was aber nicht so wichtig ist derzeit), wäre wie man es hinbekommt, dass der button, je nach verbindungsstatus seine Beschriftung und eventuelle Icons wechselt. Das jetzt aber nur am Rande
 
Zuletzt bearbeitet:
Wenn ich mich nicht irre, sollte dein erstes Problem so zu lösen sein:


ComboBox.getSelectedItem() liefert dir im ActionListener deiner ComboBox den String den du in dem JTextField eintragen willst.
über JTextField.setText("select * from " + ComboBox.getSelectedItem()) solltest du den Text im JTextField eintragen können.
Leerzeichen hinter from nicht vergessen.
code des ActionListeners etwa so:


Code:
static ActionListener al = new ActionListener() { 
	      public void actionPerformed( ActionEvent e ) 
	      {  
                  jtf.setText("select * from " + jcb_cb.getSelectedItem());
	      } 
	 };
 
Zuletzt bearbeitet:
Hab's jetzt mal versucht mit reinzunehmen, nur jetzt übernimmt er die Änderungen nicht.
Im TextField kommt jetzt "SELECT * FROM -----------"
Wenn ich jetzt eine andere Tabelle auswähle, erfolgt keine Änderung (Ich hab's auch ohne ActionListener versucht, sprich
Code:
jComboBox1.addItem(" Z ...");
    jComboBox1.getSelectedItem();
    cp.add(jComboBox1);

und:
Code:
jTextField1.setBounds(250, 48, 233, 80);
    jTextField1.setText("SELECT * FROM " + jComboBox1.getSelectedItem());
    cp.add(jTextField1);

Und da kommt das selbe.

Wo meinst du denn, sollte der ActionListener genau hin?
Je nach dem, wo ich ihn platziere muss ich entweder static zu final machen (und dann passiert nichts) oder:
Cannot make a static reference to the non-static field jComboBox1

Ich weiß, ihr habt's nich leicht mit mir :) ;-)
 
Moin,

für die zweite Realisierung würde ich Dir empfehlen,
eine eigene Klasse - für die Abwicklung Deiner Datenbank - zu erstellen.
Damit könntest Du dann einfach in den entsprechenden ActionListenern
Deiner Buttons die nötigen Methoden aufrufen.

Hier mal so eine Pseudocode-Klasse:
Java:
public class Database {

	private static Database instance = null;

	private Connection con = null;

	private Database() {
	}

	public static Database getInstance() {
		if (instance == null) {
			instance = new Database();
		}
		return instance;
	}

	public void connect() throws SQLException, ClassNotFoundException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		con = DriverManager.getConnection("jdbc:oracle:thin:@kmmaster-ts:1521:XE");
	}

	public void close() throws SQLException {
		if (con != null) {
			con.close();
			con = null;
		}
	}

	public boolean isConnected() {
		return con != null;
	}

	public void executeDBCommand(String command) throws SQLException {
		Statement stmt = con.createStatement();
		stmt.execute(command);
	}

	public ResultSet getQuery(String query) throws SQLException {
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		return rs;
	}

	public void executeTableCommand(String command) throws SQLException {
		Statement stmt = con.createStatement();
		stmt.executeUpdate(command);
	}
}
So ungefähr habe ich das mal realisiert. Ist eine Singleton-Klasse, sodass gewährleistet ist,
nur ein Objekt vom Typ Database zu besitzen. Kannst Dich ja mal dran orientieren.
Auf Deine Buttons würde ich dann einfach Methoden wie connect(), close() und executeXXXCommand() anwenden.

Zum letzten Problem:
Wenn Du die Fehlerausgabe in eine JTextArea umleiten willst,
musst Du dieses in den catch-Blocks auch kenntlich machen.
In Bezug auf meine oberen Methoden - welche fast alle eine Exception werfen -
würde es dann ungefähr so ausschauen:
Java:
try{
  Database.getInstance().close();
} catch(SQLException ex){
  DeineTextArea.append(ex.getMessage() + "\n"); // so könnte die Ausgabe aussehen
}

Hoffe, dass Dir das weiterhilft.

Gruß,
Xan
 
Zuletzt bearbeitet:
Danke Xandro, ich werd mir das mal genauer ansehen und schauen, was ich da zusammengeschustert bekomme.

Ansonsten werdet ihr noch so manchen Hilferuf von mir vernehmen :suspekt:
 
Ich hab eben in meinem Projekt an dem ich arbeite folgendes probiert:

Code:
// steht in meinen Klassenvariablen

public static JComboBox jcb_cb;
public static JTextField jtf_tf;
String[] data = {"Klaus", "Eva", "Eric", "Sphinx", "Anbetung", "Ende" };


//steht in meinem Konstruktor

frame = new JFrame("Testframe");
jtf_tf = new JTextField();

jcb_cb = new JComboBox(data);
jcb_cb.addActionListener( al );


frame.add(jtf_tf,"1,7"); // 1 und 7 spezielle koordinaten in meinem JFrame
frame.add(jcb_cb,"1,13");// 1 und 13 ebenfalls


//und dann eine Funktion

static ActionListener al2 = new ActionListener() { 
	      public void actionPerformed( ActionEvent e ) 
	      {  
 
	    	  System.out.println(jcb_cb.getSelectedItem());
	    	  jtf_tf.setText("select * from " + jcb_cb.getSelectedItem());

	      } 
	 };

Sind natürlich nur die in meinen Augen relevanten Zeilen.
Das lief sofort, wie ich es mir vorgestellt habe.
 
Zuletzt bearbeitet:
So, das Problem mit der jComboBox wäre gelöst! Danke nochmal an alle Beteiligten!(!)

Dann mach ich mich mal an die Button und die Textausgabe ran.

Was muss ich eigentlich wegen den SQL-Befehlen beachten?
Dafür is ja der "Ausführen"-Button gedacht.
 
Zuletzt bearbeitet:
Auch auf die Gefahr hin, dass es ein Doppelpost ist...

Euer Sorgenkind ist mal wieder da...

Das mit dem Trennenbutton hab ich so gelöst, dass ich einfach das ganze Fenster schließe und gut.
Die Verbindung wird dann ja automatisch geschlossen, da der "Client" ja nicht mehr da is.

Bleibt nur noch die tatsache mit dem ausführen-button.
Wie bekomm ich nun das letzte Problem gelöst?

Zur erinnerung: Ich wollte die SQL-Befehle aus meinem TextField auslesen und über Druck auf den Button zur DB senden, damit die mir die Ergebnisse in die textArea schreibt.

Hier der Teil des Problemcodes:

Code:
  import java.awt.*;
  import java.awt.event.*;
  import java.sql.*;

  import javax.swing.*;
  import javax.swing.event.*;

  import oracle.jdbc.driver.Const;

  /**
    *
    * @Beschreibung: Kleine einfache GUI zum Verbinden mit der Pumacy Oracle-Test-DB,
    * Daten auslesen und verändern mittels SQL-Befehle
    *
    * @version 1.1 vom 23.09.2008
    * @author: Florian Adler
    */

  public class Datenbank_auslesen extends JFrame {
    // Anfang Attribute
    private static String[] jComboBox1Data = {};
    private static JComboBox jComboBox1 = new JComboBox(jComboBox1Data);
    private static JTextField jTextField1 = new JTextField();
    private JButton jButton1 = new JButton();
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private static JTextArea jTextArea1 = new JTextArea("");
    private static JComboBox jComboBox2 = new JComboBox();
    private JLabel jLabel3 = new JLabel();
    private JButton jButton2 = new JButton();

     // Ende Attribute

    public Datenbank_auslesen(String title) {
      // Frame-Initialisierung
      super(title);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      int frameWidth = 730;
      int frameHeight = 575;
      setSize(frameWidth, frameHeight);
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      int x = (d.width - getSize().width) / 2;
      int y = (d.height - getSize().height) / 2;
      setLocation(x, y);
      Container cp = getContentPane();
      cp.setLayout(null);
      // Anfang Komponenten
      Font f= new Font("ComicSans", Font.BOLD, 12);
    

      jComboBox1.setFont(f);
      jComboBox1.setBounds(24, 110, 210, 24);
      jComboBox1.setBackground(Color.WHITE);
      jComboBox1.setForeground(Color.BLACK);
      jComboBox1.addItem("..........");
      jComboBox1.addItem(" 0-9 ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" A ... ");
      jComboBox1.addItem("Action");
      jComboBox1.addItem("Action2Systemrole");
      jComboBox1.addItem("AuthenticationInstrument");
      jComboBox1.addItem("AuthenticationMethod");
      jComboBox1.addItem("AuthenticationMethod2Channel");
      jComboBox1.addItem("Author2Document");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" B ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" C ...");
      jComboBox1.addItem("Category");
      jComboBox1.addItem("Category Keyword");
      jComboBox1.addItem("Change Request");
      jComboBox1.addItem("Channel");
      jComboBox1.addItem("Commentaries");
      jComboBox1.addItem("Community");
      jComboBox1.addItem("CommunityTemplates");
      jComboBox1.addItem("CommunityUser");
      jComboBox1.addItem("CommunityUsergroup");
      jComboBox1.addItem("ComminutyWorkflow");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" D ...");
      jComboBox1.addItem("Document");
      jComboBox1.addItem("DocumentArchive");
      jComboBox1.addItem("DocumentField");
      jComboBox1.addItem("DocumentFieldArchive");
      jComboBox1.addItem("DocumentHistory");
      jComboBox1.addItem("DocumentParticipants");
      jComboBox1.addItem("DocumentRating");
      jComboBox1.addItem("DocumentSignature");
      jComboBox1.addItem("DocumentTypeCategory");
      jComboBox1.addItem("DocumentTypeSequence");
      jComboBox1.addItem("Document2Category");
      jComboBox1.addItem("Document2Document");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" E ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" F ...");
      jComboBox1.addItem("Favorites");
      jComboBox1.addItem("FQSFDocument");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" G ...");
      jComboBox1.addItem("Group2WFRole");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" H ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" I ...");
      jComboBox1.addItem("IntendedReleasePeriodDate");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" J ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" K ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" L ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" M ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" N ...");
      jComboBox1.addItem("News");
      jComboBox1.addItem("Notification");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" O ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" P ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" Q ...");
      jComboBox1.addItem("QSFDocument");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" R ...");
      jComboBox1.addItem("RatingItem");
      jComboBox1.addItem("RatingType");
      jComboBox1.addItem("ReviewReleaseDate");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" S ...");
      jComboBox1.addItem("Systemrole");
      jComboBox1.addItem("Systemuser");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" T ...");
      jComboBox1.addItem("Template");
      jComboBox1.addItem("TemplateCategory");
      jComboBox1.addItem("TemplateField");
      jComboBox1.addItem("TemplateWorkflow");
      jComboBox1.addItem("TimeForInitialTraining");
      jComboBox1.addItem("TrainingParicipant");
      jComboBox1.addItem("TrainingSession");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" U ...");
      jComboBox1.addItem("Usergroup");
      jComboBox1.addItem("User2Systemrole");
      jComboBox1.addItem("User2Usergroup");
      jComboBox1.addItem("User2WFRole");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" V ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" W ...");
      jComboBox1.addItem("WFRole");
      jComboBox1.addItem("WFRole2WFStatus");
      jComboBox1.addItem("WFRole2WFTrans");
      jComboBox1.addItem("WFStatus");
      jComboBox1.addItem("WFStatusphases");
      jComboBox1.addItem("WFStatus Properties");
      jComboBox1.addItem("WFTransition");
      jComboBox1.addItem("WFTransitionConditions");
      jComboBox1.addItem("WFTransitionConstraints");
      jComboBox1.addItem("WFTransitionFinalizers");
      jComboBox1.addItem("WFTransitionProperties");
      jComboBox1.addItem("WFWorkflow");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" X ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" Y ...");
      jComboBox1.addItem("--------------------------------------------");
      jComboBox1.addItem(" Z ...");
      jComboBox1.getSelectedItem();
      jComboBox1.addActionListener(al);
      cp.add(jComboBox1);

      jTextField1.setBounds(288, 48, 393, 80);
      jTextField1.setText(""+jComboBox1.getSelectedItem());
      jTextField1.repaint();
      cp.add(jTextField1);


      jButton1.setBounds(310, 152, 175, 41);
      jButton1.setText("Ausführen");
      jButton1.addActionListener(al3);
      cp.add(jButton1);


      jLabel1.setBounds(24, 95, 150, 16);
      jLabel1.setText("Tabelle auswählen");
      jLabel1.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
      cp.add(jLabel1);

      jLabel2.setBounds(296, 24, 131, 16);
      jLabel2.setText("SQL-Befehl eingeben:");
      jLabel2.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
      cp.add(jLabel2);

      

      jTextArea1.setText("");
      jTextArea1.setBounds(64, 220, 593, 225);
      jTextArea1.setEditable(false);
      cp.add(jTextArea1);


      jButton2.setBounds(64, 152, 175, 41);
      jButton2.setText("Trennen und schließen");
      jButton2.addActionListener( new ActionListener() { 
      	  public void actionPerformed( ActionEvent e ) { 
      	    System.exit( 0 ); 
      	  } 
      	} );
      cp.add(jButton2);
      
      // Ende Komponenten

      setResizable(false);
      setVisible(true);

    }

    public static void main(String[] args) {
      new Datenbank_auslesen("Oracle-Test-Datenbank-Zugriff");
      Connection con = null;
          Statement stmt = null;
          ResultSet result = null;
          String db_Url = "jdbc:oracle:thin:@kmmaster-ts:1521:XE";
          String db_UserName = "xxxx";
          String db_UserPw = "zzzz";

     try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            }catch (Exception e) {
                  jTextArea1.setText("Treiber konnte nicht gefunden werden\n "+e);
                  }

       try{
           con = DriverManager.getConnection(db_Url, db_UserName, db_UserPw);
        }catch(Exception e) {
         e.printStackTrace();
        }
        finally{

            if(null != result) {
                try{result.close();} catch(Exception ex) {
                jTextArea1.setText(""+result);}
             }

             if(null != stmt) {
                try{stmt.close();} catch(Exception ex) {}
             }

             
          }
          }
    static ActionListener al = new ActionListener() {
        public void actionPerformed( ActionEvent e )
        {
            jTextField1.setText(""+jComboBox1.getSelectedItem());
        }
    };
    

    	static ActionListener al3 = new ActionListener() {
          public void actionPerformed( ActionEvent e )
          {
              
          	}
    		};
        
  };

Sieht jetzt alles ziemlich wüst aus in der main() aber das kommt daher weil ich immer wieder hin und her probiert habe...
 
Zuletzt bearbeitet:
Moin,

sorry, aber ich kann den Code nicht mehr sehen, diese Unordnung da drin und so weiter :rolleyes:
Da Du absolut kein OOP verwendest, wird Dich das sicherlich noch Jahre beschäftigen.
Dabei fand ich meinen Ansatz mit dem Auslagern der Datenbank-Verbindung gar nicht so schlecht ;-)

Die GUI mit main-Methode:
Java:
import java.awt.*;
import java.awt.event.*;

import java.sql.SQLException;

import javax.swing.*;

public class MainFrame extends JFrame {
    private static String[]   data        = {};
    private static JComboBox  cb_commands = new JComboBox(data);
    private static JTextField tx_sql      = new JTextField();
    private static JTextArea  ta_output   = new JTextArea("");
    private JButton           b_execute   = new JButton();
    private JLabel            jLabel1     = new JLabel();
    private JLabel            jLabel2     = new JLabel();
    private Font              f           = new Font("ComicSans", Font.BOLD, 12);
    private Database          db          = Database.getInstance();
    private JButton           b_close     = new JButton();

    public MainFrame(String title) {
        super(title);
        initialize();

        try {
            db.connect();
        } catch (SQLException ex) {
            ta_output.setText(ex.toString());
        } catch (ClassNotFoundException ex) {
            ta_output.setText(ex.toString());
        }
    }

    private void initialize() {
        Container cp = getContentPane();

        cp.setLayout(null);
        cb_commands.setFont(f);
        cb_commands.setBounds(24, 110, 210, 24);
        cb_commands.setBackground(Color.WHITE);
        cb_commands.setForeground(Color.BLACK);
        cb_commands.addItem("..........");
        cb_commands.addItem(" 0-9 ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" A ... ");
        cb_commands.addItem("Action");
        cb_commands.addItem("Action2Systemrole");
        cb_commands.addItem("AuthenticationInstrument");
        cb_commands.addItem("AuthenticationMethod");
        cb_commands.addItem("AuthenticationMethod2Channel");
        cb_commands.addItem("Author2Document");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" B ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" C ...");
        cb_commands.addItem("Category");
        cb_commands.addItem("Category Keyword");
        cb_commands.addItem("Change Request");
        cb_commands.addItem("Channel");
        cb_commands.addItem("Commentaries");
        cb_commands.addItem("Community");
        cb_commands.addItem("CommunityTemplates");
        cb_commands.addItem("CommunityUser");
        cb_commands.addItem("CommunityUsergroup");
        cb_commands.addItem("ComminutyWorkflow");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" D ...");
        cb_commands.addItem("Document");
        cb_commands.addItem("DocumentArchive");
        cb_commands.addItem("DocumentField");
        cb_commands.addItem("DocumentFieldArchive");
        cb_commands.addItem("DocumentHistory");
        cb_commands.addItem("DocumentParticipants");
        cb_commands.addItem("DocumentRating");
        cb_commands.addItem("DocumentSignature");
        cb_commands.addItem("DocumentTypeCategory");
        cb_commands.addItem("DocumentTypeSequence");
        cb_commands.addItem("Document2Category");
        cb_commands.addItem("Document2Document");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" E ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" F ...");
        cb_commands.addItem("Favorites");
        cb_commands.addItem("FQSFDocument");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" G ...");
        cb_commands.addItem("Group2WFRole");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" H ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" I ...");
        cb_commands.addItem("IntendedReleasePeriodDate");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" J ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" K ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" L ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" M ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" N ...");
        cb_commands.addItem("News");
        cb_commands.addItem("Notification");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" O ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" P ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" Q ...");
        cb_commands.addItem("QSFDocument");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" R ...");
        cb_commands.addItem("RatingItem");
        cb_commands.addItem("RatingType");
        cb_commands.addItem("ReviewReleaseDate");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" S ...");
        cb_commands.addItem("Systemrole");
        cb_commands.addItem("Systemuser");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" T ...");
        cb_commands.addItem("Template");
        cb_commands.addItem("TemplateCategory");
        cb_commands.addItem("TemplateField");
        cb_commands.addItem("TemplateWorkflow");
        cb_commands.addItem("TimeForInitialTraining");
        cb_commands.addItem("TrainingParicipant");
        cb_commands.addItem("TrainingSession");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" U ...");
        cb_commands.addItem("Usergroup");
        cb_commands.addItem("User2Systemrole");
        cb_commands.addItem("User2Usergroup");
        cb_commands.addItem("User2WFRole");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" V ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" W ...");
        cb_commands.addItem("WFRole");
        cb_commands.addItem("WFRole2WFStatus");
        cb_commands.addItem("WFRole2WFTrans");
        cb_commands.addItem("WFStatus");
        cb_commands.addItem("WFStatusphases");
        cb_commands.addItem("WFStatus Properties");
        cb_commands.addItem("WFTransition");
        cb_commands.addItem("WFTransitionConditions");
        cb_commands.addItem("WFTransitionConstraints");
        cb_commands.addItem("WFTransitionFinalizers");
        cb_commands.addItem("WFTransitionProperties");
        cb_commands.addItem("WFWorkflow");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" X ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" Y ...");
        cb_commands.addItem("--------------------------------------------");
        cb_commands.addItem(" Z ...");
        cb_commands.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                tx_sql.setText(cb_commands.getSelectedItem().toString());
            }
        });
        cp.add(cb_commands);
        tx_sql.setBounds(288, 48, 393, 80);
        cp.add(tx_sql);
        b_execute.setBounds(310, 152, 175, 41);
        b_execute.setText("SQL-Befehl ausführen");
        b_execute.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    db.executeDBCommand(tx_sql.getText());
                } catch (SQLException ex) {
                    ta_output.setText(ex.toString());
                }
            }
        });
        cp.add(b_execute);
        jLabel1.setBounds(24, 95, 150, 16);
        jLabel1.setText("Tabelle auswählen");
        jLabel1.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
        cp.add(jLabel1);
        jLabel2.setBounds(296, 24, 131, 16);
        jLabel2.setText("SQL-Befehl eingeben:");
        jLabel2.setFont(new Font("MS Sans Serif", Font.PLAIN, 13));
        cp.add(jLabel2);
        ta_output.setText("");
        ta_output.setBounds(64, 220, 593, 225);
        ta_output.setEditable(false);
        cp.add(ta_output);
        b_close.setBounds(64, 152, 175, 41);
        b_close.setText("Verbindung trennen");
        b_close.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    db.close();
                } catch (SQLException ex) {
                    ta_output.setText(ex.toString());
                }
            }
        });
        cp.add(b_close);
    }

    public static void main(String[] args) {
        MainFrame frame = new MainFrame("Oracle-Test-Datenbank-Zugriff");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(730, 575);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
Die Datenbank-Klasse:
Java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.driver.Const;

public class Database {
    private static Database instance    = null;
    private Connection      con         = null;
    private String          db_Url      = "jdbc:oracle:thin:@kmmaster-ts:1521:XE";
    private String          db_UserName = "xxxx";
    private String          db_UserPw   = "zzzz";

    private Database() {}

    public static Database getInstance() {
        if (instance == null) {
            instance = new Database();
        }

        return instance;
    }

    public void connect() throws SQLException, ClassNotFoundException {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        con = DriverManager.getConnection(db_Url, db_UserName, db_UserPw);
    }

    public void close() throws SQLException {
        if (con != null) {
            con.close();
            con = null;
        }
    }

    public boolean isConnected() {
        if (con != null) {
            return true;
        }

        return false;
    }

    public void executeDBCommand(String command) throws SQLException {
        Statement stmt = con.createStatement();

        stmt.execute(command);
    }

    public ResultSet getQuery(String query) throws SQLException {
        Statement stmt = con.createStatement();
        ResultSet rs   = stmt.executeQuery(query);

        return rs;
    }

    public void executeTableCommand(String command) throws SQLException {
        Statement stmt = con.createStatement();

        stmt.executeUpdate(command);
    }
}
Pack die einfach beide zusammen in ein Projekt und teste es mal.


Gruß,
Xan
 
Sorry Xandro, aber ich beschäftige mich noch nicht so lange mit dem Thema OOP und mir wurde bis jetzt auch nich wirklich gezeigt, wie man solch schwerwiegenden Themen behandelt und obendrein noch mit einem besseren Stil schreibt.

In den Büchern werden ja meist nur solche kleinen Sachen behandelt, die schnell nachzutippen sind und demnach nur eine Klasse etc benötigen, also nur sehr einfach gestrickt sind.

Aber ich werd deinen Vorschlag mal durchspielen...
 

Neue Beiträge

Zurück