I'm working in with a JTabbedPane, I need to add a close button in the tabs to close the current one.
I have been searching and as I understand I must extend from JPanel and add the close button as they say here
But, is there a way to add the close buttons extending JTabbedPane or is there a easier way to do it?
Thanks in advance, I really appreciate your time and your help.
Essentially, you're going to need to supply a "renderer" for the tab. Take a look at JTabbedPane.setTabComponentAt(...) for more information.
The basic idea is to supply a component that will be laid out on the tab.
I typically create a JPanel, onto which I add a JLabel (for the title) and, depending on what I want to display, some kind of control that acts as the close action.
tabPane.addTab(title, tabBody);
int index = tabPane.indexOfTab(title);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(title);
JButton btnClose = new JButton("x");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
pnlTab.add(lblTitle, gbc);
gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(btnClose, gbc);
tabPane.setTabComponentAt(index, pnlTab);
btnClose.addActionListener(myCloseActionHandler);
Now somewhere else, I establish the action handler...
public class MyCloseActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Component selected = tabPane.getSelectedComponent();
if (selected != null) {
tabPane.remove(selected);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
Now, you just as easily use any component you like and attach a mouse listener to it and monitor the mouse clicks...
Updated
The above example will only remove the currently active tab, there are a couple of ways to fix this.
The best is to probably provide some means for the action to find the tab it's associated with...
public class MyCloseActionHandler implements ActionListener {
private String tabName;
public MyCloseActionHandler(String tabName) {
this.tabName = tabName;
}
public String getTabName() {
return tabName;
}
public void actionPerformed(ActionEvent evt) {
int index = tabPane.indexOfTab(getTabName());
if (index >= 0) {
tabPane.removeTabAt(index);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
This uses the name of tab (as used with JTabbedPane#addTab) to find and then remove the tab and its associated component...
I found a tab example (from the java site) that appears to do that, at least in theirs. (Though I thought, when I tried it in the past, that it also closed the currently selected tab, though it works properly when you run their example, though I think when I updated it to work on a tabbed java notepad, it was closing the currently selected tab, though maybe I did it wrong.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Yes, my thing is working now! This WILL work for the actual tab, rather than the currently selected tab!
Hopefully you have got the answer to your question. I want to give a link that was very useful for me.
JTabbedPane with a close button
Here is some code as well.
public static void createAndShowGUI()
{
JFrame frame = new JFrame("Tabs");
frame.setMinimumSize(new Dimension(500, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel();
panel.setOpaque(false);
tabbedPane.add(panel);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel), getTitlePanel(tabbedPane, panel, "Tab1"));
JPanel panel1 = new JPanel();
panel1.setOpaque(false);
tabbedPane.add(panel1);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel1), getTitlePanel(tabbedPane, panel1, "Tab2"));
JPanel panel2 = new JPanel();
panel2.setOpaque(false);
tabbedPane.add(panel2);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel2), getTitlePanel(tabbedPane, panel2, "Tab3"));
JPanel panel3 = new JPanel();
panel3.setOpaque(false);
tabbedPane.add(panel3);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel3), getTitlePanel(tabbedPane, panel3, "Tab4"));
frame.add(tabbedPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
I made some changes in the code of oracle.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Giving the possibility to add an icon to the tab , plus the close tab button. Hope that helps.
public static void addTag(JTabbedPane tab, String title, Icon icon, int index){
MouseListener close = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//your code to remove component
//I use this way , because I use other methods of control than normal: tab.remove(int index);
}
};
final ButtonClose buttonClose = new ButtonClose (title, icon, close );
tab.setTabComponentAt(index, buttonClose);
tab.validate();
tab.setSelectedIndex(index);
}
public class ButtonClose extends JPanel {
public ButtonClose(final String title, Icon icon, MouseListener e) {
JLabel ic = new JLabel(icon);
ic.setSize(icone.getIconWidth(), icone.getIconHeight());
JLabel text= new JLabel(title);
text.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
ButtonTab button = new ButtonTab();
button.addMouseListener(e);
button.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
JPanel p = new JPanel();
p.setSize(getWidth() - icone.getIconWidth(), 15);
p.add(text);
p.add(button);
add(ic);
add(p);
}
private class ButtonTab extends JButton {
public ButtonTab() {
int size = 13;
setPreferredSize(new Dimension(size, size));
setToolTipText("Close");
setUI(new BasicButtonUI());
setFocusable(false);
setBorderPainted(false);
addMouseListener(listener);
setRolloverEnabled(true);
}
#Override
public void updateUI() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(new Color(126, 118, 91));
if (getModel().isRollover()) {
g2.setColor(Color.WHITE);
}
int delta = 3;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
g2.dispose();
}
}
private final MouseListener listener = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setContentAreaFilled(true);
button.setBackground(new Color(215, 65, 35));
}
}
#Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setContentAreaFilled(false); //transparent
}
}
};
}
Check out Peter-Swing here. It has a JClosableTabbedPane class in it, as well as many others.
When you download the jar file you can run it and have examples of all the classes.
You can have a JLabel named "x" and use the mouseListener
private final JLabel l = new JLabel(); // this is the label for tabbedPane
private final JLabel b = new JLabel("x");//Close Button
if (closeable)
{
b.setToolTipText("Click to close");
b.setOpaque(false);
b.setBackground(Color.gray);
b.addMouseListener(new MouseAdapter()
{
#Override
public void mouseExited(MouseEvent e)
{
b.setBorder(bordere);
b.setOpaque(false);
}
#Override
public void mouseEntered(MouseEvent e)
{
b.setBorder(borderl);
}
#Override
public void mouseReleased(MouseEvent e)
{
b.setOpaque(false);
b.repaint();
if (b.contains(e.getPoint()))
{
b.setBorder(borderl);
if (confirmTabClosing())
{
tab.remove(tabIndex());
if(tab.getTabCount() == 0)
spacialTabComponent.maximizeOrRestore.doClick();
}
}
else
b.setBorder(bordere);
}
#Override
public void mousePressed(MouseEvent e)
{
b.setOpaque(true);
b.repaint();
}
});
b.setBorder(bordere);
add(b, getLeftAlignedBothFilledGBC(1, 0, new Insets(0, 0, 0, 0), 0, 0));
}
}
jbCloseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int index = jtbMainTabbedPane.indexOfTabComponent(jbCloseButton);
jtbMainTabbedPane.remove(index);
}
});
Related
I want my GUI to draw circles/rectangles on the exact position I coded in the method paintComponent when I click on the respective buttons.
But I just don't know how to go on. What should I tell actionPerformed to do? Trying for a few hours to figure out a way, but I'm only getting errors.
public class Kreise extends JFrame {
Kreise() {
setLayout(new GridLayout(2, 1));
JLabel label = new JLabel("Draw Circ / Rect here: ");
label.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel jp1 = new JPanel();
jp1.setBackground(Color.LIGHT_GRAY);;
jp1.add(label);
JPanel jp2 = new JPanel(new FlowLayout());
JButton circ = new JButton("Circle");
JButton rect = new JButton("Rectangle");
circ.addActionListener(new KRListener(true));
rect.addActionListener(new KRListener(false));
jp2.add(circ);
jp2.add(rect);
MyPanel obj = new MyPanel();
jp1.add(obj);
add(jp1);
add(jp2);
setSize(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public class MyPanel extends JPanel {
public boolean circleZ = true;
public void paintComponent(Graphics g) {
if (circleZ = true) {
super.paintComponent(g);
g.drawOval(150, 50, 50, 50);
} else if (circleZ = false) {
super.paintComponent(g);
g.drawRect(150, 50, 50, 50);
}
}
}
public class KRListener implements ActionListener {
boolean b;
KRListener(boolean b) {
this.b = b;
}
public void actionPerformed(ActionEvent e) {
?
}
}
public static void main(String[] args) {
new Kreise();
}
}
Presuming I understand the question clearly (you wish to toggle between the a rectangle or circle), in the ActionListener implementation you need to:
Toggle the appropriate boolean value
Call repaint on the JPanel instance that performs the painting
One way to accomplish these steps is to have a single toggle JButton, and pass an instance of the JPanel used for drawing to your ActionListener implementation, which can be used to accomplish both steps above:
public class KRListener implements ActionListener {
private MyPanel panel;
KRListener(MyPanel panel) {
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent e) {
panel.circleZ = !panel.circleZ;
panel.repaint();
}
}
And when you paint:
if ( circleZ ){
g.drawOval(150, 50, 50, 50);
}else{
g.drawRect(150, 50, 50, 50);
}
I dont know what you are using the global boolean variable b for But I noticed that you have to call the repaint() method when you press the Button.
public class KRListener implements ActionListener {
boolean b;
KRListener(boolean b) {
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e){
//add some code here to change properties of the drawing before calling the repaint method?
repaint();
}
}
as you can see in the image above, I've a tabbed pane. On the tab header I've a JLabel (Tab Test) and a JButton (X). They are placed next to each other but I want them to have a small gap to look natural.
I've tried with a Box but it has the same background has the text making it not look natural as well. The Box has no setBorders method.
Here's how it look like with a Box:
Here's my code:
System.out.println("NewTableEvent!!!!");
final String tittle = table.getTabName();
JButton jButtonClose = new JButton("X");
jButtonClose.setBorderPainted(false);
jButtonClose.setBorder(null);
JPanel tabComponent = new JPanel(new BorderLayout());
tabComponent.add(new JLabel(tittle), BorderLayout.WEST);
tabComponent.setToolTipText("Close this tab.");
Component box = Box.createRigidArea(new Dimension(25,0));
tabComponent.add(box, BorderLayout.CENTER);
tabComponent.add(jButtonClose, BorderLayout.EAST);
// rightTabbedPane.addTab(null, table.getTable());
rightTabbedPane.addTab(null, new JPanel());
// Get total tabs
final int totalTabs = rightTabbedPane.getComponentCount();
System.out.println("Total tabs: " + totalTabs);
// Set the custom tab component
rightTabbedPane.setTabComponentAt(0, tabComponent);
So, how can I make space the JLabel and JButton and keep the background from that distance neutral?
I wasn't able to test it, but I believe you would just have to tell the box to not be opaque before you add it to the tabComponent:
box.setOpaque(false);
Hopefully, that should work for you.
EDIT
You may be able to set borders around the label and button to accomplish this:
JLabel label = new JLabel(tittle);
tabComponent.add(label);
//add more space between the label and the button
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
tabComponent.add(jButtonClose);
Demo at: http://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
Thanks to #Gavin Markee, I came up with this solution:
First, create this new class (It's the exact same class given in the example from Gavin MArkee's link, I'm just posting it here in case it is romoved in the future):
public class ButtonTabComponent extends JPanel {
private final JTabbedPane pane;
public ButtonTabComponent(final JTabbedPane pane) {
// Unset default FlowLayout' gaps
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
if (pane == null) {
throw new NullPointerException("TabbedPane is null");
}
this.pane = pane;
setOpaque(false);
//make JLabel read titles from JTabbedPane
JLabel label = new JLabel() {
#Override
public String getText() {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
return pane.getTitleAt(i);
}
return null;
}
};
add(label);
//add more space between the label and the button
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
//tab button
JButton button = new TabButton();
add(button);
//add more space to the top of the component
setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
}
private class TabButton extends JButton implements ActionListener {
public TabButton() {
int size = 17;
setPreferredSize(new Dimension(size, size));
setToolTipText("close this tab");
//Make the button looks the same for all Laf's
setUI(new BasicButtonUI());
//Make it transparent
setContentAreaFilled(false);
//No need to be focusable
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
//Making nice rollover effect
//we use the same listener for all buttons
addMouseListener(buttonMouseListener);
setRolloverEnabled(true);
//Close the proper tab by clicking the button
addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
pane.remove(i);
}
}
//we don't want to update UI for this button
#Override
public void updateUI() {
}
//paint the cross
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
//shift the image for pressed buttons
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.BLACK);
if (getModel().isRollover()) {
g2.setColor(Color.MAGENTA);
}
int delta = 6;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
g2.dispose();
}
}
private final static MouseListener buttonMouseListener = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
}
}
#Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
};
}
And then when you create your tabe you just have to:
tabbedPane.addTab(myTabTitle, myTable);
tabbedPane.setTabComponentAt(tabIndex, new ButtonTabComponent(tabbedPane));
When I set the window to non-opaque,the font look like changed!Who can tell me why and help me ,thanks!
I guess this is affected by the "RenderingHints.KEY_ANTIALIASING",but I test in many way,and ther is no my desired result.
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setUndecorated(true);
AWTUtilities.setWindowOpaque(frame, false);
JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
mainPanel.add(new JLabel("Why this changed?"));
JLabel lbl2 = new JLabel() {
#Override
public void paint(Graphics g) {
// super.paint(g);
// ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawString("There is no change", 0, 15);
}
};
lbl2.setPreferredSize(new Dimension(240, 22));
mainPanel.add(lbl2);
JPanel toolPanel = new JPanel(new FlowLayout());
final JCheckBox ckxWindowOpaque = new JCheckBox("WindowOpaque");
ckxWindowOpaque.setSelected(!AWTUtilities.isWindowOpaque(frame));
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean b = AWTUtilities.isWindowOpaque(frame);
if (b == !ckxWindowOpaque.isSelected()) return;
if (b) {
AWTUtilities.setWindowOpaque(frame, false);
} else {
AWTUtilities.setWindowOpaque(frame, true);
}
}
};
ckxWindowOpaque.addActionListener(al);
toolPanel.add(ckxWindowOpaque);
toolPanel.add(new JButton(new AbstractAction("Exit") {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}));
frame.getContentPane().add(toolPanel, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
((JComponent) frame.getContentPane()).setBorder(BorderFactory.createLineBorder(Color.black));
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setBounds(200, 200, 200, 200);
frame.setVisible(true);
}
This will have to do with how Swing/AWT deals with the different requirements between an opaque and transparent window and changes being made internally to the anti aliasing.
For example, if I use
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
To render the text, I can get it to appear the same way when it's made transparent
I also get the same result from VALUE_TEXT_ANTIALIAS_DEFAULT, VALUE_TEXT_ANTIALIAS_GASP
But if I use VALUE_TEXT_ANTIALIAS_LCD_HBGR or VALUE_TEXT_ANTIALIAS_LCD_HRGB it will act the same as the JLabel in both modes
These are system level decisions and I don't think you can effect them (easily).
You might like to take a look at LCD Text: Anti-Aliasing on the Fringe, which is an interesting read, but I'm not sure it will help much...
I have been debugging and tracing my program,and I found the key code here:SwingUtilities2.drawString/drawChars/drawTextAntialiased.
So,I modified the JRE's code in the "SwingUtilities2.drawString/drawChars",I add code like this :
if (UIManager.getBoolean("MYLAF.AATextInfo.Disable")) {
g.drawChars(data, offset, length, x, y);
return nextX;
}
Finally,on the begin of my program,I add the setting "UIManager.put("MYLAF.AATextInfo.Disable",true)".
If you wan't modify the SwingUtilities2,you can use "myJComponent.setClientProperty(AA_TEXT_PROPERTY_KEY,null)".
I have some code here, and when the button is pressed, I'm trying to extend the JPanel. However, it remains at the height it was previously. Is there a way to do this or is it fixed on the dimensions it was set when it was created?
public class GUITest extends JFrame {
JPanel jp;
JButton one;
public static void main(String[] args) {
new GUITest();
}
public GUITest() {
initWidgets();
}
public void initWidgets() {
setSize(250, 250);
setTitle("Stretch Panel Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
one = new JButton("Click me!");
ActionListener extend = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
}
//System.out.println(jp.getHeight());
}
};
one.addActionListener(extend);
add(one, BorderLayout.NORTH);
jp = new JPanel();
jp.setBackground(Color.BLACK);
jp.setPreferredSize(new Dimension(200,70));
add(jp, BorderLayout.CENTER);
setVisible(true);
}
}
alternatively, you can call revalidate() on the jpanel after the button click
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
**jp.revalidate();**
}
//System.out.println(jp.getHeight());
}
to clarify, once you change the dimensions, it has to be redrawn. the thing has been changed, but it hasn't been told to update that change visually
You should use the validate() method in order to do that.
I hope i was able to help!
Have a great day!
try this:
jp.setSize(new Dimension(200,(i+70)));
instead of jp.setPreferredSize(new Dimension(200,(i+70)));
in this code on eachclick the size will be increase by 10 :
ActionListener extend = new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent e) {
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
System.out.println("in listener");
}
};
one more thing setPrefferedsize is the default size which is called whenever component re-validates. to change the setPrefferedSize on each click :
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
jp.setPreferredSize(new Dimension(100+count,70+count));
I want to add/hide/remove jlayeredpanes dynamically on runtime and also should hide the contents on each pane when another pane is selected. I have tried the following code and i am not sure how to do this. The following code hides the content of each pane when alternate pane is selected but it does not hide its content constantly. When we mousemove over the hidden content area they are made visible again. Plz help me out in this!!
public class floorsetup {
public static void createfloor(String name)
{
String name1=name+"_pane";
JButton b = new JButton(name);
final JLayeredPane jp = new JLayeredPane();
jp.setName(name1);
floor_plan.dynamicPane_floors.put(name1, jp);
//jp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jp.setAutoscrolls(true);
jp.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jp.setMinimumSize(new java.awt.Dimension(1000, 700));
jp.setOpaque(true);
jp.setBounds(floor_plan.ground.getBounds());
floor_plan.jLayeredPane2.add(jp);
jp.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
//floor_plan.jLayeredPane2.setVisible(false);
int x = 0,y = 0;
//ComponentOrientation componentOrientation = jLayeredPane2.getComponentOrientation();
// Rectangle bounds = jLayeredPane2..getBounds();
// x=bounds.x;
//y=bounds.y;
//System.out.println(bounds);
x=evt.getX();
y=evt.getY();
System.out.println(x);
System.out.println(y);
// String name=floor_plan.table_name.getText();
String name="some name";
if(floor_plan.delete!=1)
tablesetup.addButton(name,x,y, (JLayeredPane) evt.getSource());
System.out.println((evt.getSource()));
}
});
b.setActionCommand(name);
b.setAlignmentX(Component.CENTER_ALIGNMENT);
b.setPreferredSize(new Dimension(125, 25));
b.setBackground(Color.green);
floor_plan.floors.add(b);
floor_plan.floors.add(Box.createRigidArea(new Dimension(10, 15)));
// b.setSize(125, 25);
floor_plan.dynamicButtons_floors.put(name, b);
MouseListenerClass M1 = new MouseListenerClass();
MouseClass M2 = new MouseClass();
b.addMouseMotionListener(M1);
b.addMouseListener(M2);
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(floor_plan.delete==1)
{
removeButton(evt.getActionCommand());
}
else if(floor_plan.edit==1)
{
String edit_name = JOptionPane.showInputDialog("Name of the button:");
JButton source = (JButton) evt.getSource();
source.setActionCommand(edit_name);
source.setText(edit_name);
floor_plan.dynamicButtons_floors.put(edit_name, source);
}
else
{
String switcher=evt.getActionCommand();
switcher+="_pane";
switch_pane(switcher,evt);
}
}
});
floor_plan.floors.validate();
floor_plan.floors.repaint();
}
public static void removeButton(String name) {
JButton b = floor_plan.dynamicButtons_floors.remove(name);
floor_plan.jLayeredPane2.remove(b);
floor_plan.jLayeredPane2.invalidate();
floor_plan.jLayeredPane2.repaint();
}
public static void switch_pane(String name,ActionEvent evt)
{
JLayeredPane jp = floor_plan.dynamicPane_floors.get(name);
System.out.println(floor_plan.jLayeredPane2);
System.out.println(jp);
floor_plan.ground.setVisible(false);
floor_plan.ground.setEnabled(false);
jp.setVisible(true);
jp.moveToFront(floor_plan.ground);
}
}
This is the bit of code using getText(). but i am getting error!!
if(floor_plan.delete==1)
{
JButton source = (JButton) evt.getSource();
int index=floor_plan.floors.getComponentCount();
int val=0;
Component[] components = floor_plan.floors.getComponents();
for(int i=0; i<index;i++)
{
System.out.println(source.getName());
if(components[i].getText().equals(source.getName()))
{
val=i;
}
}
removeButton(evt.getActionCommand(),val);
}
It sounds like you might want to look at the JTabbedPane. This will allow you to have multiple tabs with different content in each tab. When a user selects a tab, only the content on that tab is shown.
Links:
JTabbedPane Javadocs
JTabbedPane Tutorial
To dynamically add a tab through a button, you could use code similar to the following:
JButton newTabButton = new JButton("Add Tab");
newTabButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel newTab = new JPanel();
newTab.setLayout(null);
// Dynamic panel is a JTabbedPane
dynamicPanel.addTab(JOptionPane.showInputDialog("Name of tab"), newTab);
}
});