0

我正在处理这个应用程序,但我无法让 GUI 正确显示。我正在使用 FlowLayout,一切看起来都很混乱(任何其他布局看起来更糟)。如果只有某种方法可以在部分之间添加水平规则,那将起作用,但我尝试过的任何方法都不起作用。

这是我的代码:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;


public class ConnectToDB implements ActionListener {
    public static void main(String[] args){

        //GUI STUFF
        //constants
        final int windowX = 640; //pixels
        final int windowY = 655; //pixels
        final int fieldX = 20;   //characters
        final FlowLayout LAYOUT_STYLE = new FlowLayout();

        //window
        JFrame window = new JFrame("Mike's MySQL GUI Client");

        //Connection Details
        JLabel enterInfo = new JLabel("Enter Connection Details: ");
        JLabel driver = new JLabel("Database Driver: ");
        JTextField driverText = new JTextField(fieldX);
        JLabel dburl = new JLabel("Database URL: ");
        JTextField dburlText = new JTextField(fieldX);
        JLabel dbuser = new JLabel("Username: ");
        JTextField dbuserText = new JTextField(fieldX);
        JLabel dbpass = new JLabel("Password: ");
        JTextField dbpassText = new JTextField(fieldX);

        //Enter a SQL Command
        JLabel enterSQL = new JLabel("Enter a SQL Command:");
        JTextArea enterSQLText = new JTextArea(10, 30);

        //Connection Status and Command Buttons
        JLabel connectionStatus = new JLabel ("No Connection Now");
        JButton connectButton = new JButton("Connect");
        JButton executeButton = new JButton("Execute SQL Command");
        JButton clearCommandButton = new JButton("Clear Command");

        //SQL Execution Result
        JLabel executionResult = new JLabel("SQL Execution Result:");
        JButton clearResultsButton = new JButton("Clear Results");
        JTextArea executionResultText = new JTextArea(20, 50);

        //Configure GUI
        window.setSize(windowX, windowY);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        driverText.setEditable(false);
        dburlText.setEditable(false);
        dbuserText.setEditable(false);
        dbpassText.setEditable(false);
        executionResultText.setEditable(false);

        //Register Event Listeners
        connectButton.addActionListener(null);
        executeButton.addActionListener(null);
        clearCommandButton.addActionListener(null);
        clearResultsButton.addActionListener(null);

        //Construct Container
        Container c = window.getContentPane();

        c.setLayout(LAYOUT_STYLE);

        c.add(enterInfo);
        c.add(driver);
        c.add(driverText);
        c.add(dburl);
        c.add(dburlText);
        c.add(dbuser);
        c.add(dbuserText);
        c.add(dbpass);
        c.add(dbpassText);
        c.add(connectionStatus);
        c.add(connectButton);
        c.add(enterSQL);
        c.add(enterSQLText);
        c.add(executeButton);
        c.add(clearCommandButton);
        c.add(new JSeparator(SwingConstants.VERTICAL));
        c.add(executionResult);
        c.add(clearResultsButton);
        c.add(executionResultText);

        window.setVisible(true);//END GUI STUFF

        //DB Connection details
        System.out.println("Attempting to connect to database...");
        Connection conn = null;
        String url = "jdbc:mysql://localhost/";
        String dbName = "project3";
        String DBdriver = "com.mysql.jdbc.Driver";
        String userName = "root"; 
        String password = "OMGnpw=-0";

        driverText.setText(DBdriver);
        dburlText.setText(url);
        dbuserText.setText(userName);
        dbpassText.setText(password);

        try 
        {
          //Connect to DB and notify user
          Class.forName(DBdriver).newInstance();
          conn = DriverManager.getConnection(url+dbName,userName,password);
          System.out.println("Connected to the database");

          /*>>>>>>Do everything you need to do while connected to DB<<<<<<*/

          //HOW TO EXECUTE A STATEMENT AND PRINT IT
          //Create a statement
          Statement statement = conn.createStatement();
          //Execute a statement
          ResultSet resultSet = statement.executeQuery("SELECT * FROM riders");
          //Process query results
          ResultSetMetaData metaData = resultSet.getMetaData();
          int numberOfColumns = metaData.getColumnCount();

          for(int i = 1; i<= numberOfColumns; i++){
              System.out.printf("%20s\t", metaData.getColumnName(i));
          }
          System.out.println();

          while (resultSet.next()){
              for (int i = 1; i <= numberOfColumns; i++){
                  System.out.printf("%20s\t", resultSet.getObject(i));
              }
              System.out.println();
          }
          /*>>>>>>Finish DB activities<<<<<<*/

          //Disconnect from DB
          conn.close(); 
          System.out.printf("Disconnected from database");
        } 
        catch (Exception e) {
        e.printStackTrace();
        }
    }

    public void actionPerformed(ActionEvent e){
        System.out.println("Button Works!");
    }
}

我可能需要使用不同的布局,但 FlowLayout 是我唯一熟悉的布局。谁能建议一个简单的解决方法?

4

2 回答 2

2

尝试盒子布局。并添加一些面板。使面板流动布局并在每个面板中放置一对标签和文本字段

|-----container with box layout-----|
panel[[flow]label texfield] 
panel[[flow]label texfield] 
panel[[flow]label texfield] 
panel[[flow]label texfield] 
panel[[flow]label texfield] 
panel[[flow]sqltextfields] 
panel[[flow]buttons] 
|-----------------------------------|

并在底部附近放置您的 sql 文本字段和按钮

http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

于 2012-10-24T01:10:40.223 回答
1

所以,我们在你身边玩一点就可以实现这个...

这使用了卡片布局、边框布局、网格包布局和流布局的组合

连接窗格...

在此处输入图像描述

查询窗格

在此处输入图像描述

public class TestLayout11 {

    public static void main(String[] args) {
        new TestLayout11();
    }

    public TestLayout11() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new SQLPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class SQLPane extends JPanel {

        private ConnectionPane connectionPane;
        private QueryPane queryPane;

        public SQLPane() {

            setLayout(new CardLayout(8, 8));

            connectionPane = new ConnectionPane();
            connectionPane.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    // Perform login...
                    ((CardLayout) getLayout()).show(SQLPane.this, "query");

                }
            });
            queryPane = new QueryPane();

            add(connectionPane, "connection");
            add(queryPane, "query");

            ((CardLayout) getLayout()).show(this, "connection");

        }
    }

    public static class ConnectionPane extends JPanel {

        protected static final int FIELD_CHARACTER_WIDTH = 20;   //characters
        private JButton connectButton;
        private JTextField driverText;
        private JTextField dburlText;
        private JTextField dbuserText;
        private JTextField dbpassText;

        public ConnectionPane() {

            JLabel enterInfo = new JLabel("Enter Connection Details: ");
            JLabel driver = new JLabel("Database Driver: ");
            driverText = new JTextField(FIELD_CHARACTER_WIDTH);
            JLabel dburl = new JLabel("Database URL: ");
            dburlText = new JTextField(FIELD_CHARACTER_WIDTH);
            JLabel dbuser = new JLabel("Username: ");
            dbuserText = new JTextField(FIELD_CHARACTER_WIDTH);
            JLabel dbpass = new JLabel("Password: ");
            dbpassText = new JTextField(FIELD_CHARACTER_WIDTH);

            setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = 2;
            gbc.insets = new Insets(2, 2, 2, 2);
            add(enterInfo, gbc);
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = 1;
            gbc.gridy++;
            add(driver, gbc);
            gbc.gridy++;
            add(dburl, gbc);
            gbc.gridy++;
            add(dbuser, gbc);
            gbc.gridy++;
            add(dbpass, gbc);

            gbc.gridx++;
            gbc.gridy = 1;
            gbc.anchor = GridBagConstraints.WEST;
            add(driverText, gbc);
            gbc.gridy++;
            add(dburlText, gbc);
            gbc.gridy++;
            add(dbuserText, gbc);
            gbc.gridy++;
            add(dbpassText, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridwidth = 2;
            connectButton = new JButton("Connect");
            add(connectButton, gbc);
        }

        public void addActionListener(ActionListener listener) {
            connectButton.addActionListener(listener);
        }

        public void removeActionListener(ActionListener listener) {
            connectButton.removeActionListener(listener);
        }
    }

    public static class QueryPane extends JPanel {

        private JTextArea enterSQLText;

        public QueryPane() {

            JLabel enterSQL = new JLabel("Enter a SQL Command:");
            enterSQLText = new JTextArea(10, 30);
            JButton clearResultsButton = new JButton("Clear Results");
            JButton executeButton = new JButton("Execute SQL Command");

            setLayout(new BorderLayout());

            add(enterSQL, BorderLayout.NORTH);
            add(new JScrollPane(enterSQLText));

            JPanel buttons = new JPanel();
            buttons.add(executeButton);
            buttons.add(clearResultsButton);
            add(buttons, BorderLayout.SOUTH);

            executeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Execute query...
                    String text = enterSQLText.getText();
                    enterSQLText.setText("I've being executed....");
                }
            });

            clearResultsButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    enterSQLText.setText(null);
                }
            });

        }
    }
}
于 2012-10-24T01:55:17.390 回答