gpt4 book ai didi

Java Swing 对齐按钮、标签和文本字段

转载 作者:行者123 更新时间:2023-12-02 11:54:18 24 4
gpt4 key购买 nike

我正在尝试将 JButton 和 JTextArea 并排对齐到代码的底部中间。我遵循了一些教程并达到了这一点。当我执行程序时,文本区域和按钮仍然在顶部对齐。救命!

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class Main extends JFrame implements ActionListener{

JPanel panel = new JPanel();
JButton button = new JButton("Confirm!");
JTextArea text = new JTextArea(1, 20);
public Main() {
super("Battleship!");
setLayout(new FlowLayout());
button.addActionListener(this);
setSize(600, 500);
setResizable(true);
button.setLayout(new FlowLayout(FlowLayout.CENTER));
text.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(text, BorderLayout.SOUTH);
panel.add(button, BorderLayout.SOUTH);
add(panel);

setVisible(true);
}
public static void main(String[] args) {
new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
button.setText(text.getText());
}

}

最佳答案

请参阅代码注释中的注释。

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

public class MainLayout extends JFrame {

// A panel defaults to flow layout. Use the default
JPanel panel = new JPanel();
JButton button = new JButton("Confirm!");
JTextArea text = new JTextArea(1, 20);

public MainLayout() {
super("Battleship!");
//setLayout(new FlowLayout()); // use the default border layout
setSize(600, 500); // should be packed after components added.
//setResizable(true); // this is the default
/* Don't set layouts on things like buttons or text areas
This is only useful for containers to which we add other
components, and it is rarely, if ever, useful to add components
to these types of GUI elements. */
//button.setLayout(new FlowLayout(FlowLayout.CENTER));
// text.setLayout(new FlowLayout(FlowLayout.CENTER));

/* No need for layout constraints when adding these to
a flow layout */
//panel.add(text, BorderLayout.SOUTH);
panel.add(text);
//panel.add(button, BorderLayout.SOUTH);
panel.add(button);

// NOW we need the constraint!
add(panel, BorderLayout.PAGE_END);

setVisible(true);
}

public static void main(String[] args) {
/* Swing/AWT GUIs should be started on the EDT.
Left as an exercise for the reader */
new MainLayout();
}
}

关于Java Swing 对齐按钮、标签和文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47705925/

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