Reputation: 1029
I have written the following code but the components of tabs are not shown....in fact I want to create tabs dynamically when I enter something in the text-box...the created tabs should contain a new text-field and button. this code is a sample and after it is completed I have another question.
please let me know where I have made mistake.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
public class TestingTab extends JFrame {
private JTextField jTextField1;
private JButton jButton1;
static ArrayList<JPanel> ary = new ArrayList<JPanel>();
private int tabIndex=0;
static int index=0;
private JTabbedPane tabbedPane;
/**
* @param args
*/
public TestingTab(){
super("Testing Tab Frame");
setLayout(null);
Handler but1 = new Handler();
jTextField1 = new JTextField();
jTextField1.setVisible(true);
jTextField1.setBounds(12, 12, 85 , 30);
add(jTextField1);
jButton1 = new JButton("Button1");
jButton1.setVisible(true);
jButton1.setBounds(130, 12, 85, 30);
add(jButton1);
jButton1.addActionListener(but1);
tabbedPane = new JTabbedPane();
tabbedPane.setBounds(12, 54, 200, 220);
tabbedPane.setVisible(false);
add(tabbedPane);
pack();
setSize(250,110);
}
private class Handler implements ActionListener{
public void actionPerformed(ActionEvent evt){
String input = jTextField1.getText();
setSize(250,330);
JPanel inst = createPanel(input);
inst.setVisible(true);
tabbedPane.addTab(Integer.toString(tabIndex), inst);
tabbedPane.setVisible(true);
}
}
protected JPanel createPanel(String input){
JPanel inst = new JPanel();
inst.setVisible(true);
inst.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED),input));
JTextField textField = new JTextField();
textField.setVisible(true);
JButton button = new JButton();
button.setVisible(true);
inst.setLayout(null);
inst.add(button);
inst.add(textField);
ary.add(inst);
tabIndex=index;
index++;
return inst;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestingTab inst = new TestingTab();
inst.setVisible(true);
}
}
Upvotes: 1
Views: 133
Reputation: 21223
You're using null layout when creating a panel. That's the reason the components are not displayed. When layout property is null, the container uses no layout manager. This is called absolute positioning. In case of absolute positioning you must specify size and location of components. Absolute positing approach has many drawbacks and should be taken into consideration with care. Null layouts should/can be avoided in most cases.
Remove inst.setLayout(null);
and you will see the button and text field.
Check out A Visual Guide to Layout Managers and Using Layout Managers for more details on layout managers.
Upvotes: 4