Java 给出适合组件的布局

Java 给出适合组件的布局,java,swing,layout,layout-manager,Java,Swing,Layout,Layout Manager,我正在努力为我的Swing组件提供一个良好的布局。目前使用的是FlowLayoutbeing,但它看起来并不漂亮。我的要求是在顶行显示标签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.s

我正在努力为我的Swing组件提供一个良好的布局。目前使用的是
FlowLayout
being,但它看起来并不漂亮。我的要求是在顶行显示标签
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();
    }
}
import java.awt.*;
导入java.awt.event.*;
导入java.io.File;
导入java.sql.*;
导入java.util.Vector;
导入javax.swing.*;
导入javax.swing.table.DefaultTableModel;
公共类r_search_1扩展JFrame实现ActionListener{
jframe1;
JLabel l0,l1,l2;
JComboBox c1;
按钮b1;
连接con;
结果集rs,rs1;
报表st、st1;
编制报表pst;
字符串ID;
静态JTable表=新JTable();;
String[]columnNames={“节名”、“报告名”、“联系人”、“链接”};
串从;
向量v=新向量();
JMenuBar菜单=新建JMenuBar();
r_搜索_1()
{
frame1=新JFrame(“yippee”);
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setLayout(新的FlowLayout());
l0=新的JLabel(“获取搜索结果…”);
l0.设置前景(颜色:蓝色);
l0.setFont(新字体(“衬线”,Font.BOLD,20));
l1=新的JLabel(“搜索”);
b1=新按钮(“提交”);
l0.立根(100,50,350,40);
l1.立根(75、110、75、20);
b1.立根(150、150、150、20);
b1.添加ActionListener(本);
框架1.添加(l0);
框架1.添加(l1);
//框架1.添加(b1);
frame1.setVisible(true);
框架1.设置大小(1000400);
尝试
{
File dbFile=新文件(“executive_db.accdb”);
字符串路径=dbFile.getAbsolutePath();
con=DriverManager.getConnection(“jdbc:odbc:Driver={Microsoft Access驱动程序(*.mdb,*.accdb)};DBQ=“+path”);
forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
st=con.createStatement();
rs=st.executeQuery(“从Index1中选择索引名称”);
while(rs.next())
{
ids=rs.getString(1);
v、 添加(ID);
}
c1=新的JComboBox(v);
c1.setEditable(真);c1.setSelectedItem(“”);
c1.立根(150、110、150、20);
框架1.添加(c1);
框架1.添加(b1);
圣克洛斯();
rs.close();
}捕获(例外e){
}
//setVisible(真);
}
已执行的公共无效行动(行动事件ae){
如果(ae.getSource()==b1){
showTableData();
}
}
public void showTableData()
{
//frame1=新的JFrame(“数据库搜索结果”);
//frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//frame1.setLayout(新的FlowLayout());
DefaultTableModel=新的DefaultTableModel();
model.setColumnIdentifiers(columnNames);
表2.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
表.setFillsViewPerthweight(真);
JScrollPane scroll=新的JScrollPane(表);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HorizontalScrollBar,根据需要);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL\u SCROLLBAR\u根据需要);
from=(字符串)c1.getSelectedItem();
字符串节_name=“”;
字符串报告_name=“”;
字符串contact_name=“”;
字符串链接=”;
尝试
{
pst=con.prepareStatement(“选择不同的节。节名称,报告。报告名称,报告。链接,联系人。联系人名称”
+“从((报告上的节内部联接报告。节\u ID=节。节\u ID)联系人上的内部联接联系人。联系人\u ID=报告。联系人\u ID)度量上的左联接度量。报告\u ID=报告。报告\u ID”
+“其中Section.Section_Name(如“%”+from+“%”或Report.Report_Name(如“%”+from+“%”或Metrics.Metric_Name(如“%”+from+“%”)或Contact.Contact_Name(如“%”+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”);
addRow(新对象[]{section\u name,report\u name,contact\u name,link});
i++;
}
if(i<1){
showMessageDialog(null,“未找到记录”,“错误”,JOptionPane.Error\u消息);
}
如果(i==1){
System.out.println(i+“找到记录”);
}否则{
System.out.println(i+“找到记录”);
}
}捕获(例外情况除外){
showMessageDialog(null,例如getMessage(),“Error”,JOptionPane.Error_MESSAGE);
}
frame1.添加(滚动);
frame1.setVisible(true);
//框架1.设置大小(1000400);
//表1.close()
}
公共静态void main(字符串参数[]){
新的r_搜索_1();
}
}
这是我的要求:

笔记
  • 它被命名为
    PoorlySpecifiedLayout
    ,因为您忘记了有关..的部分。。“和(如果可调整大小)具有额外的宽度/高度。”
  • UI自然比上面看到的要高。为了制作更好的截图,它被缩短了


  • 编辑:根据安德鲁·汤普森的建议-图片


    下面是一个示例,说明如何使用
    BorderLyout
    搜索/提交行和表,并将标题添加到边框标题而不是标签中:

    public class Search extends JFrame  {
    
        private final static String TITLE = "Fetching Search Results";
        private final static String[] COLUMN_HEADERS = {"Section name", "Report name", "Contact", "Link"};
        private final static String[] SEARCH_OPTIONS = {"AAAAA", "BBBBB"};
    
        Search() {
    
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), TITLE, TitledBorder.CENTER, TitledBorder.TOP, new Font("Arial", Font.PLAIN, 20), Color.RED));
    
            JPanel topPanel = new JPanel();
            JLabel searchLabel = new JLabel("Search:");
            JComboBox<String> searchBox = new JComboBox<>(SEARCH_OPTIONS);
            JButton submitButton = new JButton("Submit");
            topPanel.add(searchLabel);
            topPanel.add(searchBox);
            topPanel.add(submitButton);
    
            JTable table = new JTable(new String[34][4], COLUMN_HEADERS);
    
            mainPanel.add(topPanel, BorderLayout.PAGE_START);
            mainPanel.add(new JScrollPane(table));
    
            setContentPane(mainPanel);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public static void main(String args[]) {
    
            new Search();
        }
    }
    
    公共类搜索扩展了JFrame{
    私有最终静态字符串TITLE=“F
    
    public class Search extends JFrame  {
    
        private final static String TITLE = "Fetching Search Results";
        private final static String[] COLUMN_HEADERS = {"Section name", "Report name", "Contact", "Link"};
        private final static String[] SEARCH_OPTIONS = {"AAAAA", "BBBBB"};
    
        Search() {
    
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), TITLE, TitledBorder.CENTER, TitledBorder.TOP, new Font("Arial", Font.PLAIN, 20), Color.RED));
    
            JPanel topPanel = new JPanel();
            JLabel searchLabel = new JLabel("Search:");
            JComboBox<String> searchBox = new JComboBox<>(SEARCH_OPTIONS);
            JButton submitButton = new JButton("Submit");
            topPanel.add(searchLabel);
            topPanel.add(searchBox);
            topPanel.add(submitButton);
    
            JTable table = new JTable(new String[34][4], COLUMN_HEADERS);
    
            mainPanel.add(topPanel, BorderLayout.PAGE_START);
            mainPanel.add(new JScrollPane(table));
    
            setContentPane(mainPanel);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public static void main(String args[]) {
    
            new Search();
        }
    }