问题描述
我创建了一个jComboBox,但它占用了帧的全宽。如何设置宽度固定。
I have created a jComboBox but it takes the full width of the frame. how to set the width fixed.
是面板的框架和框布局的borderlayout。我在这里添加代码:
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);
}
推荐答案
宽度自动由添加到组合框的最大项的宽度。您可以使用以下方法控制显示:
The width is automatically determined by the width of the largest item added to the combo box. You can control the display by using:
comboBox.setPrototypeDisplayValue("text here");
您也可以考虑使用来控制弹出窗口大小。
You might also consider using the Combo Box Popup to control the popup size.
编辑:
由于您添加的代码显示您正在使用BoxLayout,因此您可以尝试以下操作:
Since you added code that shows you are using a BoxLayout you can try the following:
comboBox.setMaximumSize( comboBox.getPreferredSize() );
或者你可以这样做:
JPanel wrapper = new JPanel();
wrapper.add( comboBox );
panel.add( wrapper );
阅读了解这些建议的工作原理。
Read the section from the Swing tutorial on Using Layout Managers to understand how these suggestions work.
这篇关于JComboBox宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!