如何使用 javafx 设计聊天框 GUI

Sat*_*y R 0 user-interface javafx

我想使用 javafx 为聊天应用程序创建一个 GUI 界面,其中对话像其他社交网络应用程序一样对齐。例如,用户 1 的对话将始终出现在左侧,而用户 2 的对话始终出现在右侧。

作为 javafx 的初学者,我有两个想法。

  1. 创建一个列表项并将对话添加到该列表并设计每个单元格
  2. 将新标签控件添加到每个对话的布局窗格中

对于这样的 GUI,开始时的好主意是什么?

我希望 GUI 是这样的

hello
        hi, nice to meet you
same here
                how are you?
Run Code Online (Sandbox Code Playgroud)

请提出正确的做法。谢谢你。

Bo *_*lim 5

你可以用 aVBox和 multiple来做到这一点Labels,但它太贪婪了,因为在 JavaFX 中我不认为有一个Control允许多个文本对齐。Alabel可以包含文本,同时它的背景是可定制的(形状、颜色、大小...),并且VBox允许节点的垂直和有序定位。

这是一个您可以完善的小演示:

  import java.util.ArrayList;
  import java.util.List;

  import javafx.application.Application;
  import javafx.geometry.Pos;
  import javafx.scene.Scene;
  import javafx.scene.control.Button;
  import javafx.scene.control.Label;
  import javafx.scene.control.ScrollPane;
  import javafx.scene.layout.Pane;
  import javafx.scene.layout.VBox;
  import javafx.stage.Stage;


public class Launcher extends Application{

private Pane root = new Pane();
private Scene scene;

private final Button add = new Button("Add");
private final VBox chatBox = new VBox(5);
private List<Label> messages = new ArrayList<>();
private ScrollPane container = new ScrollPane();
private int index = 0;



@Override
public void start(Stage stage) throws Exception{

    initChatBox();
    root.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
    root.getChildren().addAll(container,add);
    scene = new Scene(root,300,450);
    stage.setScene(scene);
    stage.show();

}

private void initChatBox(){

    container.setPrefSize(216, 400);
    container.setContent(chatBox); 

    chatBox.getStyleClass().add("chatbox");

    add.setOnAction(evt->{

        messages.add(new Label("I'm a message"));

        if(index%2==0){

            messages.get(index).setAlignment(Pos.CENTER_LEFT);
            System.out.println("1");

        }else{

            messages.get(index).setAlignment(Pos.CENTER_RIGHT);
            System.out.println("2");

        }


        chatBox.getChildren().add(messages.get(index));
        index++;

    });



}


public static void main(String[] args) {
    launch(args); 
}

}
Run Code Online (Sandbox Code Playgroud)

样式(我更喜欢将属性放在样式中,但您可以随意将它们放在您想要的位置):

  .chatbox{

  -fx-background-color:#333333;
  -fx-min-height:400px;
  -fx-min-width:200px; 

  }

  .label{

  -fx-background-color:purple;
  -fx-text-fill:white;
  -fx-pref-height:20px;
  -fx-pref-width:200px; 

  }

 .button{

 -fx-background-color:purple;
 -fx-text-fill:white;
 -fx-pref-height:25px;
 -fx-pref-width:50px;
 -fx-translate-x:75;
 -fx-translate-y:410; 

 }
Run Code Online (Sandbox Code Playgroud)

概述 :

帮助

祝你好运 !

  • @SathyamoorthyR 实际上已经一年了,您可以评论其他更好的答案,不要犹豫,将其标记为解决方案,我发现这非常有帮助,谢谢! (2认同)