سؤال

Hey everyone I've been using this as my guide and the base for my code that I've been working on:

Java Source

What I want to do, is add a shared button across all of the panes. I dont want to declare a unique button for each one, but one that is shared. My first thought was to change the frame to boxlayout and just toss a button in after it adds the pane to the frame:

    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BoxLayout(frame, BoxLayout.PAGE_AXIS));

    //Add content to the window.
    //frame.add(new GUI(), BorderLayout.CENTER);
    frame.add(new GUI());

    //setup Find button
    //findButton.setSize(110,55);
    findButton.setText("Find"); 
    findButton.setVisible(true);

    //add button to frame
    frame.add(findButton);

However, I get a runtime error: BoxLayout can't be shared. So now I wind up here. While I look into why I'm getting this error, can someone let me know if this is the right approach?

هل كانت مفيدة؟

المحلول

Suggestions:

  • Consider placing the JButton in a JPanel that is below or above the JTabbedPane so that it is always visible, and you will only need one button.
  • Or if it must be in a component held in the tabs, then each will need its own unique JButton, but they can share the same Action, which is what I recommend you do: Create an inner private class that extends AbstractAction, create an instance of this inner class, pass it into each JButton via either the JButton's constructor or its setAction(...) method.
  • Your BoxLayout problem is completely unrelated to your original question and should not even be part of this discussion. Yes, a BoxLayout must be used in one container, and that same container should be passed into the BoxLayout. Likely you're adding it to the JFrame, but in reality this adds it to the JFrame's contentPane, and so for this to work, you must pass frame.getContentPane() into the BoxLayout's first constructor parameter:

frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));

This is one reason I don't like adding components or setting layouts directly on the top level window since it is nothing but misleading syntactic sugar.

I much prefer:

JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top