我是Java的初学者。我被分配了创建Java窗口的任务,其中任何用户都应该能够输入他们的个人数据(姓名,姓氏,性别等),然后最后点击提交按钮。
要创建此类窗口,我已使用BorderLayout
添加了GridLayout
和四个面板。我的程序的主要问题,让我卡住,是我无法将两个单选按钮放在同一行。我尝试在GridLayout
中同时使用TableLayout
和JPanel
来解决问题而没有任何成功。
这是它的外观截图:
如图所示,“F”单选按钮应放在“M”单选按钮旁边而不是下方。
这是我的代码:
import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Finestra extends JFrame
{
public Finestra ()
{
super("Dati Utente");
this.setBounds(300,50,400,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new BorderLayout());
Panel panel1 = new Panel (new GridLayout(1,1));
Panel panel2 = new Panel (new GridLayout(1,1));
Panel panel3 = new Panel (new GridLayout(5,1));
Panel panel4 = new Panel (new GridLayout(5,1));
panel1.setPreferredSize(new Dimension(100,50));
panel2.setPreferredSize(new Dimension(100,50));
panel3.setPreferredSize(new Dimension (100,200));
panel4.setPreferredSize(new Dimension (260,200));
c.add(panel1, BorderLayout.NORTH);
c.add(panel2, BorderLayout.SOUTH);
c.add(panel3, BorderLayout.WEST);
c.add(panel4, BorderLayout.EAST);
JLabel label1 = new JLabel ("Personal Data");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setFont(new Font ("Open Sans",Font.BOLD,20));
panel1.add(label1);
JLabel label2 = new JLabel ("Name");
label2.setFont(new Font ("Open Sans", Font.PLAIN,14));
label2.setBorder(new EmptyBorder(0,15,0,0));
JLabel label3 = new JLabel ("Last Name");
label3.setFont(new Font ("Open Sans", Font.PLAIN,14));
label3.setBorder(new EmptyBorder(0,15,0,0));
JLabel label4 = new JLabel ("Gender");
label4.setFont(new Font ("Open Sans", Font.PLAIN,14));
label4.setBorder(new EmptyBorder(0,15,0,0));
JLabel label5 = new JLabel ("Hobby");
label5.setFont(new Font ("Open Sans", Font.PLAIN,14));
label5.setBorder(new EmptyBorder(0,15,0,0));
JLabel label6 = new JLabel ("Nationality");
label6.setFont(new Font ("Open Sans", Font.PLAIN,14));
label6.setBorder(new EmptyBorder(0,15,0,0));
panel3.add(label2);
panel3.add(label3);
panel3.add(label4);
panel3.add(label5);
panel3.add(label6);
JTextField f1 = new JTextField();
JTextField f2 = new JTextField();
f1.setPreferredSize(new Dimension(180,30));
f2.setPreferredSize(new Dimension(180,30));
JPanel fp1 = new JPanel (), fp2 = new JPanel ();
fp1.setBorder(new EmptyBorder(15,0,0,0));
fp2.setBorder(new EmptyBorder(15,0,0,0));
fp1.add(f1);
fp2.add(f2);
panel4.add(fp1);
panel4.add(fp2);
JRadioButton button1 = new JRadioButton("M"),button2 = new JRadioButton(("F"));
button1.setHorizontalAlignment(SwingConstants.CENTER); button2.setHorizontalAlignment(SwingConstants.CENTER);
ButtonGroup bgroup1 = new ButtonGroup();
bgroup1.add(button1); bgroup1.add(button2);
panel4.add(button1); panel4.add(button2);
setVisible(true);
}
如何在同一行显示两个单选按钮?
答案 0 :(得分:1)
不是将button1
和button2
添加到panel4
,而是将其添加到具有水平布局的新JPanel
,并将新JPanel
添加到{ {1}}。
panel4