简体   繁体   中英

Multiple JButtons

given i have a button that would be added to different panels am i right to say instantiating 1 JButton is not possible?

example: added a "Cancel" Button to exit application and adding it to a Tab Pane with a certain amount of tabs.

can i do

JButton btnCancel = new JButton("Cancel");

and in one of the JPanel for the 1st tab of the JFrame tab1.add(btnCancel);

2nd tab tab2.add(btnCancel);

or must i create a new JButton for each tab pane?

..how can i make it such that the button would not make a new tab?

Use a nested layout. EG

import java.awt.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;

class CancelTab {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(3,3));
                gui.setBorder(new TitledBorder("GUI"));
                JPanel controls = new JPanel(
                    new FlowLayout(FlowLayout.CENTER,5,5));
                controls.add(new JButton("Commit"));
                controls.add(new JButton("Cancel"));

                gui.add(controls,BorderLayout.SOUTH);

                JTabbedPane tabbedPane = new JTabbedPane();

                tabbedPane.addTab("Tab 1", new JLabel("Label 1"));
                tabbedPane.addTab("Tab 2", new JLabel("Label 2"));
                gui.add(tabbedPane, BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, gui);
            }
        });
    }
}

Screen Shot

在此输入图像描述

Put it below the tab pane. So your hierarchy would look like this:

  • JFrame
    • JTabbedPane
      • JPanel for tab 1
      • JPanel for tab 2, etc.
    • JButton cancel

jleedev解决方案最好(1+),但是如果你绝对需要将它添加到每个JPanel,那么你可以创建一个用按钮的文本构造的AbstractAction,并用这个相同的AbstractAction创建新的JButton,或者你可以创建一个单个ButtonModel,由具有相同名称和操作的所有JButton共享。

If you plan for the buttons to have no function this will work. But if you plan on adding any Listeners to the objects the perform any tasks than this won't be a good option. But it could work if you were to get the parent container of the button when an action is performed and do tasks accordingly.

But either way it is more efficient and logical to create a new JButton for each use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM