【发布时间】:2021-03-31 07:49:26
【问题描述】:
我使用 Swing 框架创建了一个 JFrame,我在其中添加了一个 JButton,它将在框架上显示一个在 JPanel 上创建的表单。
我在按钮上添加了动作监听器,它按预期显示面板;
但看不到单选按钮和复选框等组件的框。
只有当我将鼠标悬停在它们上面时它们才会出现。
查看单选按钮和复选框中的其他选项:
代码如下:
package codes;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class JFrameBackground extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JLabel l1,l2,l3,l4;
JTextField t1;
JButton b1;
JRadioButton r1;
JComboBox com1;
JCheckBox chk1;
JPanel p2;
JButton b;
public JFrameBackground()
{
p2=new JPanel();
p2.setLayout(null);
p2.setBounds(250, 0, 400, 400);
add(p2);
l1 = new JLabel("Name:");
l1.setBounds(100,10,70,30);
p2.add(l1);
t1 = new JTextField();
t1.setBounds(100,50,70,30);
p2.add(t1);
l2 = new JLabel("Gender:");
l2.setBounds(100,130,70,30);
p2.add(l2);
r1 = new JRadioButton("Male");
r1.setBounds(100,150,70,30);
p2.add(r1);
r1 = new JRadioButton("Female");
r1.setBounds(150,150,70,30);
p2.add(r1);
l3 = new JLabel("Course:");
l3.setBounds(100,180,70,30);
p2.add(l3);
chk1= new JCheckBox("Bca");
chk1.setBounds(100, 200, 70, 30);
p2.add(chk1);
chk1= new JCheckBox("BBA");
chk1.setBounds(150, 200, 70, 30);
p2.add(chk1);
chk1= new JCheckBox("BCOM");
chk1.setBounds(200, 200, 70, 30);
p2.add(chk1);
l4 = new JLabel("Country:");
l4.setBounds(100,220,70,30);
p2.add(l4);
String name[] = {"India","USA","UK","Rus"};
com1=new JComboBox(name);
com1.setBounds(100, 250, 70, 30);
p2.add(com1);
b1= new JButton("Submit");
b1.setBounds(140, 300, 90, 30);
p2.add(b1);
b =new JButton("Show form");
b.setBounds(0, 4, 190, 40);
b.setFocusPainted(false);
b.setBorderPainted(false);
b.addActionListener(this);
add(b);
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
p2.setVisible(true);
}
});
Container c=getContentPane();
c.setBackground(Color.gray);
setBounds(170, 100, 1250, 500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new JFrameBackground();
}
public void actionPerformed(ActionEvent arg0)
{
}
}
【问题讨论】:
-
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
为什么 GUI 这么宽?是否将其他组件添加到此 GUI?以最小尺寸提供 ASCII 艺术或 GUI 的预期布局的简单绘图,如果可调整大小,则具有更大的宽度和高度 - 以显示应如何使用额外空间。
标签: java swing jframe layout-manager