JComboBox 宽度
我创建了一个 jComboBox,但它占据了框架的整个宽度。如何设置固定宽度。
是的,框架的边框布局和面板的框布局。我在这里添加代码:
import javax.swing.*;
import java.awt.BorderLayout;
public class Window8 {
JFrame frame;
JPanel panel;
JComboBox combo;
public void go(){
String[] option = { "STUDENT", "TEACHER" };
combo.setPreferredSize(new Dimension(1,25));
combo = new JComboBox(option);
menu.setSelectedIndex(0);
frame = new JFrame("DELETION");
frame.setLocationRelativeTo(null);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(combo);
}
I have created a jComboBox but it takes the full width of the frame. how to set the width fixed.
yes borderlayout for the frame and box layout for the panel. i am adding the code here:
import javax.swing.*;
import java.awt.BorderLayout;
public class Window8 {
JFrame frame;
JPanel panel;
JComboBox combo;
public void go(){
String[] option = { "STUDENT", "TEACHER" };
combo.setPreferredSize(new Dimension(1,25));
combo = new JComboBox(option);
menu.setSelectedIndex(0);
frame = new JFrame("DELETION");
frame.setLocationRelativeTo(null);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.NORTH,panel);
panel.add(combo);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
宽度由添加到组合框中的最大项目的宽度自动确定。您可以通过以下方式控制显示:
您还可以考虑使用 组合框Popup 控制弹出窗口的大小。
编辑:
由于您添加了显示您正在使用 BoxLayout 的代码,因此您可以尝试以下操作:
或者您可以执行以下操作:
阅读 使用布局管理器了解这些建议的工作原理。
The width is automatically determined by the width of the largest item added to the combo box. You can control the display by using:
You might also consider using the Combo Box Popup to control the popup size.
Edit:
Since you added code that shows you are using a BoxLayout you can try the following:
Or you can do something like:
Read the section from the Swing tutorial on Using Layout Managers to understand how these suggestions work.
尝试comboBox.setPreferredWidth(200);或其他一些值来设置宽度
jzd 是正确的。实际的 API 是
setPreferredSize(new Dimension(...));
try comboBox.setPreferredWidth(200); or some other value to set the width
jzd is right. The actual API is
setPreferredSize(new Dimension(...));
您可以使用框布局执行以下操作。
。
代码片段如下:
Here is something you can do with box layout.
.
code snippet below:
您可能想使用
setSize()
方法。You might want to use
setSize()
method.使用不同的布局管理器。尝试
FlowLayout
。Use a different LayoutManager. Try
FlowLayout
.不要使用 JCombobox<>() 而不是使用 Combobox<>() ,那么宽度不会改变,而且如果您设置首选大小,它也不会随 Combobox 改变,所以请使用它
Don't use JCombobox<>() instead of that use Combobox<>() then width won't change, also if you set preferred size it won't change with Combobox so use this instead