简体   繁体   中英

Can't get Java GUI Layout to Show Correctly

I'm working on this application and I just can't get the GUI to display properly. I'm using FlowLayout, and everything just looks all jumbled (any other layout looks even worse). If there were just some way to add a horizontal rule between sections, that would work, but nothing I tried works.

Here is my code:

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!");
    }
}

I may need to use a different layout, but FlowLayout is the only one I'm familiar with. Can anyone suggest an easy fix?

Try a box layout. And add some panels to it. Make the panels flow layout and put a pair of label and textfield in each panel

|-----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] 
|-----------------------------------|

and near the bottom put your sql textfields and buttons

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

So, we a little playing around you can achieve this...

This uses a combination of card layout, border layout, grid bag layout and flow layout

Connection Pane...

在此处输入图片说明

Query Pane

在此处输入图片说明

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);
                }
            });

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM