JavaFX:同时有 2 个独立窗口

2023-12-14

我想一次创建2个独立的窗口。一个窗口将能够保存可观察的列表,另一个窗口将显示所选列表对象的属性。我正在尝试将列表视图创建为通用列表,并将其与特定于对象的窗口(例如客户属性、啤酒属性、商店属性)结合起来。

简而言之:如果用户单击“客户”,它将显示包含所有客户的列表视图,并且第一个客户的属性显示在单独的、特定于客户的窗口中。

如果用户单击“商店”,它会显示相同的列表视图,但会填充商店。特定于商店的窗口也会打开,其中包含第一个商店的属性。

我尝试使用 2 个 FXMLLoaders,但由于某种原因我不知道如何使用它们。我在 JavaFX 方面很平庸,所以我什至不知道从哪里开始。这就是我所得到的,但它似乎是错误的。

 FXMLLoader loader = new FXMLLoader(getClass().getResource("List.fxml"));
 loader.setRoot(this);
 loader.setController(this);
 FXMLLoader loader2 = new FXMLLoader(getClass().getResource("StoreWindow.fxml"));
 loader2.setRoot(this);
 loader2.setController(this);
 try {
        loader.load();
        loader2.load(); 
     } catch (IOException ex) {
        throw new RuntimeException(ex);
     }

您基本上必须遵循@Slaw 的说明。创建一个Model。分享Model两者之间Controllers。观察模型电流Customer并做出相应反应。 MCVE如下:

主要类别:(使用正确的场景加载两个阶段。创建模型并将其传递给两个控制器):

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author sedri
 */
public class JavaFXApplication36 extends Application {

    @Override
    public void start(Stage stage) {
        try {
            FXMLLoader listViewFXMLLoader = new FXMLLoader(getClass().getResource("ListViewFXML.fxml"));
            Parent listViewRoot = listViewFXMLLoader.load();
            ListViewController listViewController = listViewFXMLLoader.getController();
            Scene scene1 = new Scene(listViewRoot);
            stage.setScene(scene1);           

            FXMLLoader detailsFXMLLoader = new FXMLLoader(getClass().getResource("DetailsFXML.fxml"));
            Parent detailsRoot = detailsFXMLLoader.load();
            DetailsController detailsController = detailsFXMLLoader.getController();
            Scene scene2 = new Scene(detailsRoot);
            Stage stage2 = new Stage();
            stage2.setScene(scene2);

            DataModel model = new DataModel();
            listViewController.initModel(model);
            detailsController.initModel(model);

            stage.show();
            stage2.show(); 
        } catch (IOException ex) {
            Logger.getLogger(JavaFXApplication36.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

型号类别:(了解当前客户和客户的可观察列表)

import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 *
 * @author sedrick
 */
public class DataModel {
    private final ObservableList<Customer> customerList = FXCollections.observableArrayList(customer -> new Observable[]{customer.nameProperty(), customer.ageProperty()});
    private final ObjectProperty<Customer> currentCustomer = new SimpleObjectProperty();

    public ObjectProperty<Customer> currentCustomerProperty() {
        return currentCustomer;
    }

    public void setCurrentCustomer(Customer currentCustomer) {
        this.currentCustomer.set(currentCustomer);
    }

    public Customer getCurrentCustomer() {
        return this.currentCustomer.get();
    }  


    public ObservableList<Customer> loadCustomers()
    {        
        customerList.add(new Customer("John Doe", 21));
        customerList.add(new Customer("Jane Joe", 20));

        return customerList;
    }
}

客户类别:

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
 *
 * @author sedrick
 */
public class Customer {
    private final StringProperty name = new SimpleStringProperty();
    private final IntegerProperty age = new SimpleIntegerProperty();
    public Customer(String name, int age) {
        this.name.set(name);
        this.age.set(age);
    }

    public String getName()
    {
       return this.name.get();
    }

    public void setName(String name)
    {
        this.name.set(name);
    }

    public StringProperty nameProperty()
    {
        return this.name;
    }

    public int getAge()
    {
       return this.age.get();
    }

    public void setAge(int age)
    {
        this.age.set(age);
    }

    public IntegerProperty ageProperty()
    {
        return this.age;
    }
}

列表视图控制器:(初始化模型,设置ListView并观察当前客户属性)

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;

/**
 *
 * @author sedri
 */
public class ListViewController implements Initializable {
   @FXML private ListView<Customer> listView;

   private DataModel model;



    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    

    public void initModel(DataModel model)
    {
        // ensure model is only set once:
        if (this.model != null) {
            throw new IllegalStateException("Model can only be initialized once");
        }

        listView.getSelectionModel().selectedItemProperty().addListener((obs, oldCustomer, newCustomer) -> 
            model.setCurrentCustomer(newCustomer));

        model.currentCustomerProperty().addListener((obs, oldCustomer, newCustomer) -> {
            if (newCustomer == null) {
                listView.getSelectionModel().clearSelection();
            } else {
                listView.getSelectionModel().select(newCustomer);
            }
        });

        listView.setCellFactory(lv -> new ListCell<Customer>() {
            @Override
            public void updateItem(Customer customer, boolean empty) {
                super.updateItem(customer, empty);
                if (empty) {
                    setText(null);
                } else {
                    setText("Name: " + customer.getName() +  "  Age: " + customer.getAge());
                }
            }
        });

        listView.setItems(model.loadCustomers());
    }
}

列表视图 FXML:

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication36.ListViewController">
   <children>
      <ListView fx:id="listView" prefHeight="200.0" prefWidth="200.0" />
   </children>
</StackPane>

详情控制器:(初始化模型并观察当前客户属性)

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

/**
 * FXML Controller class
 *
 * @author sedri
 */
public class DetailsController implements Initializable {
    @FXML TextField tfName, tfAge;

    private DataModel model;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    

     public void initModel(DataModel model) {
        // ensure model is only set once:
        if (this.model != null) {
            throw new IllegalStateException("Model can only be initialized once");
        }

        this.model = model ;

        model.currentCustomerProperty().addListener((observable, oldCustomer, newCustomer) -> {
            if(newCustomer == null){
                tfName.setText("");
                tfAge.setText("");
            }
            else{
                tfName.setText(newCustomer.getName());
                tfAge.setText(Integer.toString(newCustomer.getAge()));
            }
        });
    }
}

详细信息 FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>


<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication36.DetailsController">
   <children>
      <Label text="Name" />
      <TextField fx:id="tfName" />
      <Label text="Age" />
      <TextField fx:id="tfAge" />
   </children>
   <padding>
      <Insets left="20.0" right="20.0" />
   </padding>
</VBox>

更多信息:

@James D 关于模型-视图-控制器(MVC)的回答.
GitHub 代码.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaFX:同时有 2 个独立窗口 的相关文章

  • Java中有没有一种方法可以通过名称实例化一个类?

    我正在寻找问题 从字符串名称实例化一个类 https stackoverflow com questions 9854900 instantiate an class from its string name它描述了如何在有名称的情况下实例
  • 序列的排列?

    我有具体数量的数字 现在我想以某种方式显示这个序列的所有可能的排列 例如 如果数字数量为3 我想显示 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 0 2 1 0 2 2 1 0 0 1 0 1 1 0
  • 在内存中使用 byte[] 创建 zip 文件。 Zip 文件总是损坏

    我创建的 zip 文件有问题 我正在使用 Java 7 我尝试从字节数组创建一个 zip 文件 其中包含两个或多个 Excel 文件 应用程序始终完成 没有任何异常 所以 我以为一切都好 当我尝试打开 zip 文件后 Windows 7 出
  • 如何循环遍历所有组合,例如48 选择 5 [重复]

    这个问题在这里已经有答案了 可能的重复 如何在java中从大小为n的集合中迭代生成k个元素子集 https stackoverflow com questions 4504974 how to iteratively generate k
  • 使用 LinkedList 实现下一个和上一个按钮

    这可能是一个愚蠢的问题 但我很难思考清楚 我编写了一个使用 LinkedList 来移动加载的 MIDI 乐器的方法 我想制作一个下一个和一个上一个按钮 以便每次单击该按钮时都会遍历 LinkedList 如果我硬编码itr next or
  • 在 Jar 文件中运行 ANT build.xml 文件

    我需要使用存储在 jar 文件中的 build xml 文件运行 ANT 构建 该 jar 文件在类路径中可用 是否可以在不分解 jar 文件并将 build xml 保存到本地目录的情况下做到这一点 如果是的话我该怎么办呢 Update
  • 谷歌应用程序引擎会话

    什么是java应用程序引擎 默认会话超时 如果我们将会话超时设置为非常非常长的时间 会不会产生不良影响 因为谷歌应用程序引擎会话默认情况下仅存储在数据存储中 就像facebook一样 每次访问该页面时 会话仍然永远存在 默认会话超时设置为
  • 在接口中使用默认方法是否违反接口隔离原则?

    我正在学习 SOLID 原则 ISP 指出 客户端不应被迫依赖于他们所使用的接口 不使用 在接口中使用默认方法是否违反了这个原则 我见过类似的问题 但我在这里发布了一个示例 以便更清楚地了解我的示例是否违反了 ISP 假设我有这个例子 pu
  • 来自 dll 的 Java 调用函数

    我有这个 python 脚本导入zkemkeeperdll 并连接到考勤设备 ZKTeco 这是我正在使用的脚本 from win32com client import Dispatch zk Dispatch zkemkeeper ZKE
  • Java 公历日历更改时区

    我正在尝试设置 HOUR OF DAY 字段并更改 GregorianCalendar 日期对象的时区 GregorianCalendar date new GregorianCalendar TimeZone getTimeZone GM
  • Java 集合的并集或交集

    建立并集或交集的最简单方法是什么Set在 Java 中 我见过这个简单问题的一些奇怪的解决方案 例如手动迭代这两个集合 最简单的单行解决方案是这样的 set1 addAll set2 Union set1 retainAll set2 In
  • java.lang.IllegalStateException:提交响应后无法调用 sendRedirect()

    这两天我一直在尝试找出问题所在 我在这里读到我应该在代码中添加一个返回 我做到了 但我仍然得到 java lang IllegalStateException Cannot call sendRedirect after the respo
  • jdbc mysql loginTimeout 不起作用

    有人可以解释一下为什么下面的程序在 3 秒后超时 因为我将其设置为在 3 秒后超时 12秒 我特意关闭了mysql服务器来测试mysql服务器无法访问的这种场景 import java sql Connection import java
  • 像 Java 这样的静态类型语言中动态方法解析背后的原因是什么

    我对 Java 中引用变量的动态 静态类型和动态方法解析的概念有点困惑 考虑 public class Types Override public boolean equals Object obj System out println i
  • 内部类的构造函数引用在运行时失败并出现VerifyError

    我正在使用 lambda 为内部类构造函数创建供应商ctx gt new SpectatorSwitcher ctx IntelliJ建议我将其更改为SpectatorSwitcher new反而 SpectatorSwitcher 是我正
  • Spring Boot Data JPA 从存储过程接收多个输出参数

    我尝试通过 Spring Boot Data JPA v2 2 6 调用具有多个输出参数的存储过程 但收到错误 DEBUG http nio 8080 exec 1 org hibernate engine jdbc spi SqlStat
  • logcat 中 mSecurityInputMethodService 为 null

    我写了一点android应显示智能手机当前位置 最后已知位置 的应用程序 尽管我复制了示例代码 并尝试了其他几种解决方案 但似乎每次都有相同的错误 我的应用程序由一个按钮组成 按下按钮应该log经度和纬度 但仅对数 mSecurityInp
  • 关键字“table”附近的语法不正确,无法提取结果集

    我使用 SQL Server 创建了一个项目 其中包含以下文件 UserDAO java public class UserDAO private static SessionFactory sessionFactory static se
  • 专门针对 JSP 的测试驱动开发

    在理解 TDD 到底是什么之前 我就已经开始编写测试驱动的代码了 在没有实现的情况下调用函数和类可以帮助我以更快 更有效的方式理解和构建我的应用程序 所以我非常习惯编写代码 gt 编译它 gt 看到它失败 gt 通过构建其实现来修复它的过程
  • 如何使用mockito模拟构建器

    我有一个建造者 class Builder private String name private String address public Builder setName String name this name name retur

随机推荐

  • 如何使中心圆居中?

    如何使中心圆居中 仅限 CSS 假设最新的 CSS3 浏览器支持 当父 w h 动态变化时 必须保持 v h 居中 实验性 CSS 盒模型规范在这里有帮助吗 Thanks http jsfiddle net dragontheory VdJ
  • 在 MS *Word* VBA 中循环选择不连续的部分

    我在 MS Word 2013 VBA 中有一个宏 notExcel 切换所选文本的突出显示颜色 代码看起来像 这 If Selection Range HighlightColorIndex WhtColor Then Selection
  • 使用新版本的应用程序更新和更改设置 plist 文件

    我的应用程序的资源文件夹中有一个默认设置 plist 文件 并且在第一次启动时该文件被复制到文档文件夹中 在应用程序的后续版本中 如何将文档中的 plist 设置与自上一版本以来添加的任何新键和值 可能是嵌套的 合并 我见过一种模式 其中属
  • PowerShell New-CommandWrapper :为以下参数提供值

    我的意思是对输出进行着色ls 我检查了Powershell 一劳永逸地正确着色 Get Childitem 输出 这两个选项似乎是 Use New CommandWrapper 正如 OP 和 Jon Z 的回答中所提倡的那样 使用模块PS
  • R 用字典表替换列中的值而不使用合并或连接

    假设我有一个字典表 例如 id value 1 168833 2 367656 3 539218 4 892211 millions of lines 和一个原始数据框 例如 name code Abo 1 Cm3 2 LL2 6 JJ 1
  • 正确防止 Flex Mobile 应用程序中的方向变化

    有谁能够真正让它在 Flex SDK 4 6 中正常工作吗 这是一个简短的片段
  • VS2010中Boost.Thread抛出bad_alloc异常

    包括后
  • 运行时错误:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

    我是 mysql 和 jdbc 的新手 我收到了这个标题中的错误 我一整天都在寻找 找不到适合我的解决方案 我尝试过的 卸载 重新安装mysql 将mysql connector java 5 1 25 bin jar和ojdbc7 jar
  • Setter 不能与 -=、+= 等一起使用吗? [复制]

    这个问题在这里已经有答案了 我不明白为什么我会收到零错误 我正确创建了设置器 但它不接受 或 运算符后面的本身 为什么 class Test def var var 0 end def var value var value end def
  • 如何打破这个 while(true) 循环?

    您好 我试图打破这个循环 并在两个 if 语句都为 true 时返回坐标 然而 循环永远不会结束 我该如何修复它 public static String positionQuery int dim Scanner test in Scan
  • Lodash uniqBy更新最新值

    我有一系列如下所示的对象 id 27 unread message count 0 id 27 unread message count 7 我使用 lodash uniqBy 删除重复项 如下所示 uniqBy data id 它删除了重
  • iPhone iCloud 应用程序在 iOS 4 上编译时崩溃

    我想使用 iCloud 但是当我在 iOS 4 3 模拟器上编译该应用程序时 它崩溃了 dyld 找不到符号 OBJC CLASS NSMetadataQuery 我应该怎样做才能使其在 iOS 3 4 和 5 上运行 我的解决方案是 NS
  • 任意解引用指针的输出

    我将内存填充如下 char buf 8 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88 然后将 unsigned long 指针依次放在前 5 个字节上并输出结果 char c ptr unsigned lo
  • 编译 .java 文件时无法找到符号错误

    再会 我在同一目录中有两个类 Map 和 Field 我成功编译了 Field java 但是当我编译 Map java 时 我得到了这个 Map java 4 error cannot find symbol private Field
  • jQuery 创建带有 ID 的新 div?

    我的 ASP NET masterPage master 中有表单 如果我单击 提交 它会通过 ajax 调用 masterPage master cs 文件中的某些方法 我在更新面板中有它 但我想用 jQuery 改进它 所以我有这个 s
  • 代码在不应该生效的时候生效了

    我有一个功能 如果用户单击按钮 它将在文本框中显示一个值 并在单击 btn 按钮后执行另一个功能的触发 function addwindow numberAnswer gridValues btn mainNumberAnswerTxt v
  • 在 BeautifulSoup 中用字典解析脚本标签

    正在研究部分答案this问题 我遇到了一个bs4 element Tag这是一堆嵌套的字典和列表 s 以下 有没有办法返回包含的网址列表s without using re find all 关于此标签结构的其他评论也很有帮助 from b
  • Flash 图像上传需要强制裁剪吗?

    有人知道 Flash 文件 图像 上传器会强制用户在上传之前调整图像大小和 或裁剪图像吗 然后也上传它 基本上 我不希望我的服务器处理图像调整大小 裁剪 我想指定目标纵横比 并让用户调整大小并裁剪图像以使其适合 我以前见过裁剪上传器 但它们
  • 通过C连接oracle DB

    我想在Windows操作系统中使用C语言连接oracle数据库 但我不知道如何开始 以及先决条件是什么 任何人都可以为我提供任何帮助 教程或示例代码吗 谢谢 http www dreamincode net forums topic 307
  • JavaFX:同时有 2 个独立窗口

    我想一次创建2个独立的窗口 一个窗口将能够保存可观察的列表 另一个窗口将显示所选列表对象的属性 我正在尝试将列表视图创建为通用列表 并将其与特定于对象的窗口 例如客户属性 啤酒属性 商店属性 结合起来 简而言之 如果用户单击 客户 它将显示