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
JBut开发者_JS百科ton 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. E.G.
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
- JTabbedPane
jleedev solution is best (1+), but if you absolutely need to add it to each JPanel, then you can either create an AbstractAction that is constructed with the button's text and create new JButtons with this one same AbstractAction, or you could create one single ButtonModel that is shared by all JButtons that have the same name and action.
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.
精彩评论