【发布时间】:2021-12-16 10:25:19
【问题描述】:
怎么了? ImageIcon 和框架的大小工作正常。
但JTextField 和JButton 不是。
我需要解决方案。
import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Alkalmazás");
frame.setVisible(true);
frame.setSize(500,500);
frame.setResizable(false);
JTextField field = new JTextField();
field.setBounds(40,250, 300,35);
JButton button = new JButton(new ImageIcon("table.png"));
button.setBounds(40,400, 250,25);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tf.setText(""something);
}
});
frame.add(field);
frame.add(button);
}
}
【问题讨论】:
-
您不能同时将
JTextField和JButton添加到JFrame的中心。setVisible方法应在所有其他方法之后调用。 -
不要尝试使用 setBounds(...)。 Swing 旨在与布局管理器一起使用。默认情况下,JFrame 使用
BorderLayout。阅读Layout Managers 上的 Swing 教程以获取更多信息。
标签: java swing jbutton jtextfield layout-manager