gpt4 book ai didi

java - 边框和流布局不显示两个窗口?

转载 作者:行者123 更新时间:2023-12-01 12:46:59 25 4
gpt4 key购买 nike

我创建了两个方法,其参数之一为 BorderLayout,另一个为 FlowLayout,每个方法都有自己的框架。

但只有一个混合布局的弹出窗口。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JFrame;

public class BLayOut extends JFrame
{
private JFrame fr,fr2;
private JLabel label,label2,label3;

public void win(BorderLayout bl)

{
fr =new JFrame("BorderLayout");

setSize(300,200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);


setLayout(bl);

label= new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 2");
add(label,BorderLayout.NORTH);
add(label2,BorderLayout.SOUTH);
add(label3,BorderLayout.CENTER);

}

public void win(FlowLayout fl)
{
fr2 =new JFrame("FlowLayout");
setSize(500,200);
setVisible(true);
setLocation(300, 0);
setDefaultCloseOperation(EXIT_ON_CLOSE);


setLayout(fl);

label= new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 3");
add(label);
add(label2);
add(label3);

}


}

class BLayOutMain
{
public static void main (String args [])
{
BLayOut bl = new BLayOut();
bl.win(new BorderLayout());
bl.win(new FlowLayout());
}
}

最佳答案

你混淆了你的引用资料......

首先,创建一个从 JFrame 扩展的类...

public class BLayOut extends JFrame {

然后声明 JFrame 的两个实例变量...

private JFrame fr, fr2;

然后在您的方法中,创建一个 JFrame 实例并将其分配给这些变量之一并立即忽略它们...

fr = new JFrame("BorderLayout");

// Which frame are you modifying now...??
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(bl);

label = new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 2");
add(label, BorderLayout.NORTH);
add(label2, BorderLayout.SOUTH);
add(label3, BorderLayout.CENTER);

基本上,它所做的是设置 BLayOut 实例的属性,而不是 frfr2

首先从BLayOut中删除extends JFrame,这会混淆问题,这将生成一个无法找到方法的编译器错误列表。这些可以通过使用 frfr2 来修复,具体取决于方法...

fr = new JFrame("BorderLayout");

// Which frame are you modifying now...??
fr.setSize(300, 200);
fr.setVisible(true);
fr.setDefaultCloseOperation(EXIT_ON_CLOSE);

fr.setLayout(bl);

fr.label = new JLabel("Label 1");
fr.label2 = new JLabel("Label 2");
fr.label3 = new JLabel("Label 2");
fr.add(label, BorderLayout.NORTH);
fr.add(label2, BorderLayout.SOUTH);
fr.add(label3, BorderLayout.CENTER);

您确实应该只在准备好显示初始化的 UI 时调用 setVisible

fr = new JFrame("BorderLayout");
//...
fr.setVisible(true);

这样,您的 UI 将显示出来,而无需以某种方式重新验证框架...

关于java - 边框和流布局不显示两个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com