我试图将我的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());
}
}
答案 0 :(得分:1)
请参阅代码注释中的注释。
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();
}
}
答案 1 :(得分:0)
无需将任何流程布局设置为按钮或文本以放置在中心,因为默认情况下面板具有" FlowLayout center"这将组件放在中心位置
框架默认为" BorderLayout"
要将按钮和textarea放在底部,您只需要在面板中添加它们(已经完成),然后使用参数BorderLayout.SOUTH添加面板到框架。
看下面修改后的代码,它将根据您的需要工作
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!");
button.addActionListener(this);
setSize(600, 500);
setResizable(true);
panel.add(text);
panel.add(button);
add(panel, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
@Override public void actionPerformed(ActionEvent e)
{
button.setText(text.getText());
}
}