我正在开发一个Java桌面应用程序。在GUI中,我希望用户可以根据需要动态添加任意数量的工具栏。为实现这一点,以下是我已经完成的事情:
现在第一个工具栏上有一个名为“添加”的按钮,该按钮添加在“toolbar1Panel”上,而该工具栏又添加到topPanel。
现在我已经实现了上面“添加”按钮的“actionPerformed()”方法,如下所示:
// to add second toolbar Panel to the topPanel dynamically
topPanel.add(toolbar2Panel);
但问题是它不起作用。表示topPanel没有添加工具栏。
我遗失了什么吗?
代码是Netbeans Generated所以我认为它只会增加其他人的混乱,这就是我没有粘贴任何代码的原因。
答案 0 :(得分:3)
将另一个工具栏添加到BoxLayout后,您可能需要(重新进入)?验证面板。
我已经反复这样做但我无法理解3个左右的方法调用背后的逻辑;所以我只是尝试它们,直到我找到有效的那个:
topPanel.validate();
topPanel.invalidate();
topPanel.revalidate();
topPanel.layout();
(至少)其中一个应该强制你的GUI重新计算它的布局,使北面板更大,从而显示你添加的第二个(和连续的)工具栏。
答案 1 :(得分:2)
如果没有指定顶部面板的布局,可能会假设不正确。
向它添加两个工具栏面板可能只是将第一个替换为第二个,或忽略第二个。
仅用于测试将topPanel的布局设置为FlowLayout并重试。
答案 2 :(得分:0)
我认为你在测试前试图做太多。我接近这个的方式是从一个非常简单的东西开始,例如一个面板,一个静态标签。如果出现这种情况,请添加带有菜单项的工具栏。那样有用吗。然后插入地添加碎片。
很可能你会遇到一个简单案例的问题,然后可以搞清楚,或者你会有一个简单的案例在这里发帖。
另外,作为起点,从网上看一些工作实例。把它剪下来再贴上你的情况。
答案 3 :(得分:0)
有帮助吗? 这是你想要实现的目标吗?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class AddingToolbars {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
AddingToolbars me = new AddingToolbars();
me.initGui();
}
});
}
private JPanel topPanel;
private JPanel mainPanel;
private JFrame frame;
private void initGui() {
frame = new JFrame();
mainPanel = new JPanel(new BorderLayout());
frame.setContentPane(mainPanel);
topPanel = new JPanel();
BoxLayout bLayout = new BoxLayout(topPanel,BoxLayout.Y_AXIS);
topPanel.setLayout(bLayout);
mainPanel.add(topPanel,BorderLayout.NORTH);
JButton addButton = new JButton("Add toolbar");
mainPanel.add(addButton,BorderLayout.CENTER);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
addNewToolBar();
}
});
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
protected void addNewToolBar() {
JToolBar tb = new JToolBar();
tb.add(new JButton("b1"));
tb.add(new JButton("b2"));
tb.add(new JButton("b3"));
topPanel.add(tb);
mainPanel.validate();
}
}