gpt4 book ai didi

java - 如何阻止 JTextFields 脱离框架

转载 作者:行者123 更新时间:2023-11-30 04:22:18 26 4
gpt4 key购买 nike

我想阻止文本字段脱离 GUI 或在新“行”上打印文本字段。

这是代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Window extends JFrame {
private JTextField TextField0;
private JTextField TextField1;
private JCheckBox CheckBox0;
private JPanel panel;

//CONSTRUCTOR
public Window() {
super("Checkbox");
setLayout(new FlowLayout());

panel = new JPanel();
add(panel, BorderLayout.CENTER);

TextField0 = new JTextField("Add field",15);
panel.add(TextField0);
TextField1 = new JTextField("Add field", 15);

CheckBox0 = new JCheckBox("");

HandlerClass handler = new HandlerClass();
TextField0.addActionListener(handler);
}

public class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource()==TextField0) {
CheckBox0.setText(String.format("%s",event.getActionCommand()));
panel.remove(TextField0);
panel.add(CheckBox0);
panel.add(TextField1);
panel.revalidate();
panel.repaint();
}
}
}
}

最佳答案

你真的无能为力......

JTextField 将允许文本溢出文本字段的可视区域(修剪屏幕上的文本)

您可以尝试使用 JTextArea ,支持多行文本

您也可以尝试打包框架

enter image description here

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTextField {

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

public TestTextField() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

String text = "This is a long piece of text that seems to go on and on and on and on an on....and some more...";

JTextField field = new JTextField(10);
JTextArea ta1 = new JTextArea(10, 2);
JTextArea ta2 = new JTextArea(10, 2);

field.setText(text);
ta1.setText(text);
ta2.setText(text);

configure(ta1);
configure(ta2);

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.add(field, gbc);
frame.add(ta1, gbc);
frame.add(new JScrollPane(ta2), gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

protected void configure(JTextArea ta) {
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
}

});
}
}

关于java - 如何阻止 JTextFields 脱离框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16745410/

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