[英]Why is it that my JButtons do not show up when put in the constructor for the JPanel?
[英]How come my JButtons ("search buttons") wont show up on the JPanel?
我正在构建一个库存 Gui 应用程序,我希望使用描述的第一个字母来搜索项目。 因此,我需要在 JPanel 上显示 26 个小按钮(将是字母表中的字母)。 然后使用搜索按钮对应保存的文件。 但我似乎无法让按钮甚至显示??? 它只是JPanel。 我这里的只是整个程序的一个片段。 只需突出显示其中的 JPanel 和 JButton。
JPanel searchPanel = new JPanel( );
searchPanel.setPreferredSize(new Dimension(240, 160));
searchPanel.setBorder(BorderFactory.createTitledBorder("Item Search"));
searchPanel.setBounds(149, 295, 205, 94);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 7;
gridConstraints.gridwidth = 3;
gridConstraints.insets = new Insets(10, 0, 10, 0);
gridConstraints.anchor = GridBagConstraints.CENTER;
getContentPane().add(searchPanel, gridConstraints);
layeredPane.setLayer(searchPanel, 2);
layeredPane.add(searchPanel, gridConstraints);
int x = 0, y = 0;
// Create Button and Position of Search Panel
for (int i = 0; i < 26; i++)
{
JButton[ ] searchBtn = new JButton[26];
searchBtn[i] = new JButton( );
searchBtn[i].setText(String.valueOf((char) (65 + i)));
searchBtn[i].setFont(new Font("Arial", Font.BOLD, 12));
searchBtn[i].setMargin(new Insets(-10, -10, -10, -10));
searchBtn[i].setBounds(149, 295, i, i);
sizeButton(searchBtn[i], new Dimension(37, 27));
searchBtn[i].setBackground(Color.YELLOW);
searchBtn[i].setFocusable(false);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = x;
gridConstraints.gridy = y;
searchPanel.add(searchBtn[i], gridConstraints);
//Search Buttons Method
searchBtn[i].addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e)
{
searchBtnActionPerformed(e);
}
});
x++;
//6 Buttons Per Row
if (x % 6 == 0)
{
x = 0;
y++;
}
}
getContentPane( ).setLayout(getLayout( ));
}
所以,我拿走了你的代码,纠正了你试图同时添加两个不同的容器并且它产生的事实......
现在,我很确定这不是您想要的,基于我对您的代码的有限理解(这是代码处于甚至不值得尝试挽救的状态的那些时刻之一),但是,看来您显然不了解如何使用布局管理器。
您应该花时间查看在容器中布局组件
所以,我扔掉了你的代码,只是做了......
public class SearchPane extends JPanel {
public SearchPane() {
setBorder(BorderFactory.createTitledBorder("Item Search"));
setLayout(new GridLayout(-1, 6));
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
JOptionPane.showMessageDialog(SearchPane.this, "You want to search for [" + cmd + "]", "Search", JOptionPane.PLAIN_MESSAGE);
}
};
for (int index = 0; index < 26; index++) {
JButton btn = new JButton(Character.toString('A' + index));
btn.addActionListener(listener);
add(btn);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.