如何在javaswing中正确地放置组件

bweufnob  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(299)

我是新来的,我没有找到足够的教程学习它正确。所以我开始在实践中学习。我试了以下方法code:-

public class MyGui {
    private JList<String> docList;
    private JPanel mainPanel;
    private DefaultListModel<String> listDocModel;

    public MyGui(){

        listDocModel = new DefaultListModel<>();

        try (InputStream resource = MyGui.class.getResourceAsStream("/data.csv");
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8))) {
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                listDocModel.addElement(line);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        mainPanel = new JPanel();
        JLabel label = new JLabel("My list below:-");
        mainPanel.add(label);
        docList = new JList<>(listDocModel);
        mainPanel.add(docList);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("MyGui");
        frame.setContentPane(new MyGui().mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize( new Dimension( 400, 400));
        frame.pack();
        frame.setVisible(true);
    }
}


我想把标签放在屏幕左上角和列表下面。我不知道该怎么做?

4bbkushb

4bbkushb1#

将主面板与布局管理器一起使用: JPanel(LayoutManager layout) 布局管理器oracle.doc

mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//add top
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("My list below:-");
mainPanel.add(label,gbc);
docList = new JList<>(listDocModel);
//add bellow
gbc.gridy = 1;
mainPanel.add(docList,gbc);

相关问题