我是 Swing 新手。我正在尝试创建一个 800x600 的窗口,它将分为两个相等的部分 (800x300):第一个是不可变的文本区域,第二个是 - 按钮。
问题: 按钮应该占据窗口的下半部分。但是按钮大小似乎不正确。
代码:
import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
JFrame.setDefaultLookAndFeelDecorated(true);
final JFrame frame = new JFrame("Lingvo frame");
frame.setPreferredSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
final JButton showResultButton = new JButton();
showResultButton.setPreferredSize(new Dimension(800, 300));
showResultButton.setHorizontalAlignment(SwingConstants.CENTER);
showResultButton.setVerticalAlignment(SwingConstants.BOTTOM);
frame.add(panel);
panel.add(showResultButton);
frame.pack();
frame.setVisible(true);
showResultButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showResultButton.setText("translation");
}
});
}
}
最佳答案
只需将您的框架设置为 GridLayout
。另请注意,只需使用此构造函数 JtextArea(rows, columns)
设置 JTextArea
的大小,并仅设置 pack()
您的框架。无需将大小设置为任何内容。 GridLayout
将根据 JTextArea
JButton
的大小
此外,Swing 应用程序应该从事件调度线程运行。参见 Initial Threads .
另见 Laying out Components within a Container了解有关布局管理器的更多信息。
这是一个运行示例
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
final JFrame frame = new JFrame("Lingvo frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton showResultButton = new JButton();
final JTextArea textArea = new JTextArea(20, 60);
frame.setLayout(new GridLayout(2, 1));
frame.add(textArea);
frame.add(showResultButton);
frame.pack();
frame.setVisible(true);
showResultButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showResultButton.setText("translation");
}
});
}
});
}
}
关于java - JButton 忽略指示的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708380/