gpt4 book ai didi

java - JPanel 中的 JTextArea 中心

转载 作者:行者123 更新时间:2023-12-02 04:08:43 25 4
gpt4 key购买 nike

我不敢相信这个问题没有答案...我只想将 JTextArea 放在 JPanel 中。我正在使用 BoxLayout 来实现此目的。当我运行程序时,JTextArea 占据整个屏幕。这是为什么?

public class BLayout extends JFrame implements ActionListener {

public BLayout() {
super("GUI Testing");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel choosePanel = new JPanel();
choosePanel.setLayout(new BoxLayout(choosePanel, BoxLayout.X_AXIS));
choosePanel.setBackground(Color.BLUE);

JTextArea text = new JTextArea(1, 10);
text.setLineWrap(true);
text.setEditable(false);
text.setText("Welcome to Library Search.\n\n"
+ "Choose a command from the \"Commands\""
+ " menu above for adding a reference, "
+ "searching references, or quitting the program.");
choosePanel.add(text);
add(choosePanel);
}

如何使文本区域仅位于面板中间而不占据整个屏幕?

最佳答案

I am using BoxLayout for this. When I run my program, the JTextArea takes up the whole screen. Why is this?

因为这就是 BoxLayout 的工作原理。例如,您可以使用 GridBagLayout 来代替,它默认将组件置于容器内的中心

Example layout

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

public class BLayout extends JFrame {

public BLayout() {
super("GUI Testing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());


JTextArea text = new JTextArea(7, 40);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(false);
text.setText("Welcome to Library Search.\n\n"
+ "Choose a command from the \"Commands\""
+ " menu above for adding a reference, "
+ "searching references, or quitting the program.");
add(text);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

BLayout frame = new BLayout();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

关于java - JPanel 中的 JTextArea 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34008161/

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