What is the process of creating a Java chat window?
Swing component
JPanel
JPanel is basically the same as the Panel component in AWT. It has no border and cannot be moved. , zoom in, out, or close the panel. Its default layout manager is FlowLayout. You can also use JPanel's parameterized constructor JPanel (LayoutManager layout) or its setLayout() method to specify a layout manager for it.
JScrollPane
JScrollPane is a panel container with a scroll bar, and this panel can only add one component. If you want to add multiple components to the panel, you must add the components to JPanel , and then add the JPanel to the JScrollPane.
Common construction methods of JScrollPane
JScrollPane()//创建一个空的JScrollPane面板 JScrollPane(Component view)//创建一个显示指定组件的JScrollPane面板,只要组件的内容超过视图大小就会显示水平和垂直滚动条 JScrollPane(Component view,int vsbPolicy,int hsbPolicy)//创建一个显示指定容器并具有指定滚动条策略的JScrollPane。参数vsbPolicy和hsbPolicy分别表示垂直滚动条策略和水平滚动条策略,指定为SCrollPaneConstants的静态常量。
Methods of JScrollPane
void setHorizontalBarPolicy(int policy)//指定水平滚动条策略,即水平滚动条何时显示在滚动面板上 void setVerticalBarPolicy(int policy)//指定垂直滚动条策略,即垂直滚动条何时显示在滚动面板上 void setViewportView(Component view)//设置在滚动面板显示的组件 void setHorizontalBarPolicy(int policy)//指定水平滚动条策略,即水平滚动条何时显示在滚动面板上 void setVerticalBarPolicy(int policy)//指定垂直滚动条策略,即垂直滚动条何时显示在滚动面板上 void setViewportView(Component view)//设置在滚动面板显示的组件
How to add buttons to the container
package Swing; import javax.swing.*; import java.awt.*; public class Example02 extends JFrame{ public Example02(){ this.setTitle("PanelDemo"); //创建一个滚动面板 JScrollPane scrollPane=new JScrollPane(); //设置水平滚动条策略,---滚动条一直显示 scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); //设置垂直滚动条策略----滚动条需要时显示 scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); //定义一个面板 JPanel panel=new JPanel(); panel.add(new JButton("按钮一")); panel.add(new JButton("按钮二")); panel.add(new JButton("按钮三")); panel.add(new JButton("按钮四")); //设置JPanel面板在滚动面板中显示 scrollPane.setViewportView(panel); //将滚动面板添加到内容面板的中心区域 this.add(scrollPane, BorderLayout.CENTER); //将一个按钮添加到内容面板的SOUTH区域 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400,250); this.setVisible(true); } public static void main(String[] args) { new Example02(); } }
Text component
Text component is used to receive information entered by the user or display information to the user, including text box (JtexField) and text area (JtexArea). They have a common parent class JTextComponent. This is an abstract class that provides commonly used methods for text components.
Common methods of text components
Method description | Function description |
---|---|
String getText() | Returns all text content in the text component |
String getSeletedText() | Returns the selected text component Text content |
void selectAll() | Select all content in the text component |
void setEditable() | Set the text component to be editable or non-editable |
void setText(String text) | Set the content of the text component |
void replaceSelection(String content) | Replace the currently selected content with the given content |
Text box (JTextField)
Can only accept input of a single line of text. Commonly used construction methods of text boxes
Method description | Function description |
---|---|
JTextField() | Create an empty text box, the initial string is null |
JTextField(int columns) | Create a text box with the specified number of columns, and the initial string is null |
JTextField(String text) | Create a text box that displays the specified initial string. Text box |
JTextField(String text,intcolumn) | Create a text box with the specified number of columns and display the specified initial string |
Text Area (JTextArea)
Can receive multiple lines of text input, you can set the number of rows and columns in the area, common construction methods
Method description | Function description |
---|---|
JTextArea(String text) | Create and display the specified initial string Text field |
JTextArea() | Create an empty text field |
JTextArea(int rows,int columns) | Create an empty text area with specified rows and columns |
JTextArea(String text,int rows,int columns) | Create a display specifying the initial Text and specify the text field of rows and columns |
Chat window example
package Swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LiaoTian extends Frame { JButton sendBt; JTextField inputField; JTextArea chatContent; public LiaoTian(){ this.setLayout(new BorderLayout()); //创建一个文本域 chatContent=new JTextArea(12,34); //创建一个滚动面板,将文本域作为显示条件 JScrollPane showPanel=new JScrollPane(chatContent); //设置文本域为不可编辑 chatContent.setEditable(false); //创建一个面板 JPanel inputPanel=new JPanel(); //创建一个文本框 inputField =new JTextField(20); //创建一个发送按钮 sendBt=new JButton("发送"); //为按钮添加事件 sendBt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //获取输入的信息 String content=inputField.getText(); //判断输入的信息是否为空 if(content!=null&&!content.trim().equals("")){ chatContent.append("本人:"+content+"\n"); }else{ chatContent.append("聊天信息不能为空"+"\n"); } inputField.setText(""); } }); //创建一个标签 Label label=new Label("聊天信息"); //将标签添加到Jpanel面板 inputPanel.add(label); //将按钮添加到Jpanel面板 inputPanel.add(inputField); //将滚动面板和JPanel面板添加到JFrame窗口 inputPanel.add(sendBt); this.add(showPanel,BorderLayout.CENTER); this.add(inputPanel,BorderLayout.SOUTH); this.setTitle("聊天窗口"); this.setSize(400,300); this.setVisible(true); } public static void main(String[] args) { new LiaoTian(); } }
Running results
From the above, we can simulate a simple window through JFrame. First, we divide the window into two areas through the BorderLayout layout manager, then put a JScrollPane scrolling panel in the center area, and add a JTextArea text field in the scrolling panel. , used to display chat records, a JPanel panel is placed in the south area, and three components are placed in the JPanel panel. The JLabel label is used for information description, the JTextField text box is used to enter the user's chat information, and the JButton button is used to send chat information. . The JLabel component used here is a static component, used to display a line of static text and icons. Its function is information description. It does not accept user input and cannot add events.
The above is the detailed content of What is the process of creating a Java chat window?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
