簡體   English   中英

Java擺動布局和/或標簽不按順序排列

[英]Java swing layouts and/or labels not in order

我有一個應該顯示以下內容的窗口:

  • JLablel“您以前使用過GUI嗎?” 在頂部,居中
  • 它下面有兩個radioButtons“Yes”和“No”,有點在中間,有點向左
  • 一個JButton“NEXT”在右下角

所有三個元素都應該有綠色字體和darkGrey背景。 問題是出現的窗口看起來不像我想要的那樣。 這是我的代碼:

        yesButton = new JRadioButton(yes);
        //yesButton.setMnemonic(KeyEvent.VK_B); // doesn't work?
        yesButton.setActionCommand(yes);            

        noButton = new JRadioButton(no);
        // noButton.setMnemonic(KeyEvent.VK_C); // doesn't work?
        noButton.setActionCommand(no);

        ButtonGroup group = new ButtonGroup();
        group.add(yesButton);
        group.add(noButton);

        nextButton = new JButton("NEXT");
        nextButton.setActionCommand(next);

        yesButton.addActionListener(this);
        noButton.addActionListener(this);
        nextButton.addActionListener(this);

        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.add(yesButton);
        radioPanel.add(noButton);

        add(radioPanel, BorderLayout.WEST);
        // setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        // radioPanel.setBorder(new EmptyBorder(250, 250, 20, 20));
            // there is no difference between the above two, right?

        String q = "Have you used GUI before?";
        JPanel area = new JPanel(new BorderLayout());

        area.setBackground(Color.darkGray);
        JLabel textLabel2 = new JLabel("<html><div style=\"text-align: center;\">"
                + q + "</html>", SwingConstants.CENTER);
        textLabel2.setForeground(Color.green);
        Font font2 = new Font("SansSerif", Font.PLAIN, 30);
        textLabel2.setFont(font2);
        //textLabel2.setBorder(new EmptyBorder(0, 0, 250, 0)); //top, left, bottom, right
        area.add(textLabel2, BorderLayout.NORTH);
        area.add(nextButton, BorderLayout.EAST);
        add(area, BorderLayout.CENTER);

我覺得我快到了,謝謝你的幫助!

--EDIT--截圖: 截圖

您需要使用嵌套面板。

  1. 對於BorderLayout.NORTH,您可以直接添加JLabel。 您需要將水平文本對齊設置為居中。
  2. 對於單選按鈕,您可以使用FlowLayout創建JPanel,然后將按鈕添加到面板並將面板添加到CENTER。
  3. 對於按鈕,使用右對齊的FlowLayout將按鈕添加到面板,然后將面板添加到SOUTH。

還有其他選擇。 您還可以使用Vertical BoxLayout作為主面板的布局,然后將子面板添加到其中。

只使用BorderLayout,您將無法獲得太多控制權。 嘗試其他類似MigLayout或Java的其他許多布局管理器(GridBag,Box )。

MigLayout中,它看起來像:

area.setLayout(new MigLayout("fill"));

area.add(textLabel2, "wrap");
area.add(radioPanel, "wrap");
area.add(nextButton, "tag right");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM