编程语言
首页 > 编程语言> > java-提供适合组件的布局

java-提供适合组件的布局

作者:互联网

我正在努力为我的Swing组件提供良好的布局.当前使用的是FlowLayout,但看起来并不漂亮.我的要求是在顶行显示标签l0.然后,第二列中的标签l1,组合框c1和按钮b1(居中对齐).最后,输出显示在下面的Jtable中.我该怎么做呢?

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class r_search_1 extends JFrame implements ActionListener {

    JFrame frame1;
    JLabel l0, l1, l2;
    JComboBox c1;
    JButton b1;
    Connection con;
    ResultSet rs, rs1;
    Statement st, st1;
    PreparedStatement pst;
    String ids;
    static JTable table  = new JTable();;
    String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
    String from;
    Vector v = new Vector();
    JMenuBar menu = new JMenuBar();

    r_search_1() 
    {


          frame1 = new JFrame("yippee");
          frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame1.setLayout(new FlowLayout());

        l0 = new JLabel("Fetching Search Results...");
        l0.setForeground(Color.blue);
        l0.setFont(new Font("Serif", Font.BOLD, 20));
        l1 = new JLabel("Search");
        b1 = new JButton("submit");

        l0.setBounds(100, 50, 350, 40);
        l1.setBounds(75, 110, 75, 20);
        b1.setBounds(150, 150, 150, 20);
        b1.addActionListener(this);

        frame1.add(l0);
        frame1.add(l1);
        //frame1.add(b1);
        frame1.setVisible(true);
        frame1.setSize(1000, 400);


        try 
        {

            File dbFile = new File("executive_db.accdb");
            String path = dbFile.getAbsolutePath();
            con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            st = con.createStatement();
            rs = st.executeQuery("select index_name from Index1");
           while (rs.next())
           {
                ids = rs.getString(1);
                v.add(ids);

            }
            c1 = new JComboBox(v);
            c1.setEditable(true);c1.setSelectedItem("");
            c1.setBounds(150, 110, 150, 20);

            frame1.add(c1);
            frame1.add(b1);
            st.close();
            rs.close();
        } catch (Exception e) {
        }
       // setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b1) {
            showTableData();
        }
     }

    public void showTableData()
    {

        // frame1 = new JFrame("Database Search Result");
      //  frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //frame1.setLayout(new FlowLayout());
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);

        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        from = (String) c1.getSelectedItem();

        String section_name = "";
        String report_name = "";
        String contact_name = "";
        String link = "";


        try
        {

        pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
                        + "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID )  LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID  "
                        + " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
            ResultSet rs = pst.executeQuery();
            int i = 0;
            while (rs.next()) {
                section_name = rs.getString("Section_Name");
                report_name = rs.getString("Report_Name");
                contact_name = rs.getString("Contact_Name");
                link = rs.getString("Link");
                model.addRow(new Object[]{section_name, report_name, contact_name, link});
                i++;
            }
            if (i < 1) {
                JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (i == 1) {
                System.out.println(i + " Record Found");
            } else {
                System.out.println(i + " Records Found");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
      //  frame1.setSize(1000, 400);
        //table.close()
    }

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

这是我的要求:

解决方法:

笔记

>之所以命名为PoorlySpecifiedLayout,是因为您忘记了“ ..”和“(如果可调整大小)具有额外宽度/高度的部分.”
>用户界面自然比上面看到的要高.它被缩短以制作更好的屏幕截图.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class PoorlySpecifiedLayout {

    // the GUI as seen by the user (without frame)
    JPanel ui = new JPanel(new BorderLayout(5,5));
    String[] comboValues = {
        "String to pad combo."
    };
    String[] tableHeader = {
        "Section Name","Report Name","Contact","Link"
    };
    String[][] tableBody = {{"", "", "", ""}};

    PoorlySpecifiedLayout() {
        initUI();
    }

    public final void initUI() {
        ui.setBorder(new EmptyBorder(20,20,20,20));

        JPanel top = new JPanel(new BorderLayout(15, 5));
        ui.add(top, BorderLayout.PAGE_START);

        top.add(new JLabel(
                "Fetching search results", SwingConstants.CENTER));
        JPanel controls = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 5));
        top.add(controls, BorderLayout.PAGE_END);
        controls.add(new JLabel("Search:"));
        controls.add(new JComboBox(comboValues));
        JButton submit = new JButton("submit");
        Insets padButton = new Insets(5,20,5,20);
        submit.setMargin(padButton);
        controls.add(submit);
        JTable table = new JTable(tableBody, tableHeader);
        ui.add(new JScrollPane(table));
    }

    public final JComponent getUI(){
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
             PoorlySpecifiedLayout psl = new PoorlySpecifiedLayout();   

                JFrame f = new JFrame("Poorly Specified Layout");
                f.add(psl.getUI());
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See https://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

标签:layout,swing,layout-manager,java
来源: https://codeday.me/bug/20191029/1960779.html