如何在表/面板/ JFrame中使用SWING/JButton正确定位按钮

Ler*_*ica 3 java swing

我正在从文件中读取信息并将其放在表格中.该代码,这不是我的,但我是需要什么,所以我试图保持它,让它为我有用的.我需要添加5-6按钮和它们的功能,但作为全新的与工作有什么SWING我有很艰难的时期既完成-保持我现有的代码并添加在适当位置的按钮.

这是我的文件,第一部分是表格的制作地点,我尝试在其中包含一个按钮的代码:

public class DataFileTable extends JPanel {
  public DataFileTable(String dataFilePath) {
    JTable table;
    DataFileTableModel model;
    Font f;

    f = new Font("SanSerif",Font.PLAIN,24);
    setFont(f);
    setLayout(new BorderLayout());

    model = new DataFileTableModel(dataFilePath);

    table = new JTable();
    table.setModel(model);
    table.createDefaultColumnsFromModel();
    //Try to add button
    JButton button = new JButton("First Button");
    button.setSize(80,20);
    button.setVerticalAlignment(SwingConstants.BOTTOM);
    button.setHorizontalAlignment(SwingConstants.RIGHT);
    //End button part
    JScrollPane scrollpane = new JScrollPane(table);
    scrollpane.add(button);//Add button 
    add(scrollpane);

    }
Run Code Online (Sandbox Code Playgroud)

第二部分主要是main功能:

public Dimension getPreferredSize(){ 

    return new Dimension(400, 300);
    }

 public static void main(String s[]) {
    JFrame frame = new JFrame("Data File Table");
    DataFileTable panel;

    panel = new DataFileTable("customers.dat");

    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setForeground(Color.black);
    frame.setBackground(Color.lightGray);
    frame.getContentPane().add(panel,"Center");

    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    frame.addWindowListener(new WindowCloser());
    }
 }

class WindowCloser extends WindowAdapter {
 public void windowClosing(WindowEvent e) {
   Window win = e.getWindow();
   win.setVisible(false);
   System.exit(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我用这段代码得到的PrintScreen:

在此输入图像描述

我不是在寻找最好的外观和感觉,但如果我能保留当前的代码并在底部的某处添加按钮,那将是非常好的.我尝试将按钮直接添加到框架中main,frame.add(button)然后即使我设置了一个大小,按钮占用了所有空间,桌子也不再可见.

Aub*_*bin 7

您不能执行以下操作:

JScrollPane scrollpane = new JScrollPane(table);
scrollpane.add(button);//Add button 
add(scrollpane);
Run Code Online (Sandbox Code Playgroud)

因为滚动窗格只能有一个显示表格的视口.

我建议:

add(scrollpane, BorderLayout.CENTER );
Run Code Online (Sandbox Code Playgroud)

JToolBar toolbar = new JToolBar();
toolbar.add( button1 );
toolbar.add( button2 );
toolbar.add( button3 );
...
add( toolbar, BorderLayout.NORTH );
Run Code Online (Sandbox Code Playgroud)

查看JToolBar的文档