How to create Combobox with multiselection? - java

I need to create a combo box with multi-selection, how to achieve that?

I know, that the question is rather old, but for those, who still looks for solution of this problem, try the following code:
public class ComboSelections {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel((LookAndFeel) Class.forName("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel").newInstance());
final JPopupMenu menu = new JPopupMenu();
JMenuItem one = new JCheckBoxMenuItem("One");
JMenuItem two = new JCheckBoxMenuItem("Two");
JMenuItem three = new JCheckBoxMenuItem("Three");
JMenuItem four = new JCheckBoxMenuItem("Four");
menu.add(one);
menu.add(two);
menu.add(three);
menu.add(four);
final JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!menu.isVisible()) {
Point p = button.getLocationOnScreen();
menu.setInvoker(button);
menu.setLocation((int) p.getX(),
(int) p.getY() + button.getHeight());
menu.setVisible(true);
} else {
menu.setVisible(false);
}
}
});
one.addActionListener(new OpenAction(menu, button));
two.addActionListener(new OpenAction(menu, button));
three.addActionListener(new OpenAction(menu, button));
four.addActionListener(new OpenAction(menu, button));
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(button);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static class OpenAction implements ActionListener {
private JPopupMenu menu;
private JButton button;
private OpenAction(JPopupMenu menu, JButton button) {
this.menu = menu;
this.button = button;
}
#Override
public void actionPerformed(ActionEvent e) {
menu.show(button, 0, button.getHeight());
}
}
}

There are a few basic problems with creating custom combobox popup content (like a list with multiselection):
1. Default UI suggests JList usage as the content so to change that behavior you will have to change the whole ComboBoxUI
2. You cannot simply change the default combobox list into multiselection one due to the fact that only one value gets "selected" at the end and list has default rollover selection mouse listener, that will make you unable to choose more than one element
So i'd reccomend you to use simple JList instead of combobox or look into using some extended components libraries like JideSoft - they have this component and lots more which you won't be able to quickly create using Swing features.

Related

Method for MouseListeners and KeyListeners not working with .addMouseListener for Buttons on a Jpanel, Java

I have been having difficulty with making a method of Listeners to use repetitively in my code. Also, I am new to this, so I am very sorry for anything I leave out on this. Though, now here is my method for the Listeners:
public static void keysEvents(Optional<String> output)
{
MouseListener mouseEvents = new MouseAdapter()
{
public void mouseClick (MouseEvent mouseEvent)
{
Integer mouseModifiers = mouseEvent.getModifiers();
if ((mouseModifiers & InputEvent.BUTTON1_MASK) ==
InputEvent.BUTTON1_MASK)
{
if (output == null)
{
System.out.println("click");
}
//more options...
}
}
public void mouseRelease (MouseEvent mouseEvent)
{
}
};
//More listeners...
}
EDITED VERSION:
public static MouseListener keysEvents(Optional<String> output)
{
MouseListener mouseEvents = new MouseAdapter()
{
public void mouseClick (MouseEvent mouseEvent)
{
Integer mouseModifiers = mouseEvent.getModifiers();
if ((mouseModifiers & InputEvent.BUTTON1_MASK) ==
InputEvent.BUTTON1_MASK)
{
if (output == null)
{
System.out.println("click");
}
//more options...
}
}
public void mouseRelease (MouseEvent mouseEvent)
{
}
};
//More listeners...
return mouseEvents;
//How would I have it return different listeners?
}
Here is the code for the program's window:
JPanel MainP = new JPanel();
MainP.setLayout(new GridLayout(4, 2, 100, 30));
frame.setLayout(new GridLayout(1, 2));
frame.setBackground(Color.blue);
JPanel _B1_ = new JPanel();
JPanel _B2_ = new JPanel();
JPanel _B3_ = new JPanel();
JPanel _B4_ = new JPanel();
Button _Continue_ = new Button("Continue");
Button _Load_Game_ = new Button("Load Game");
Button _Settings_ = new Button("Settings");
Button _Exit_ = new Button("Exit");
_Continue_.addMouseListener(keysEvents(Optional.of(""))); //<edited here.
_Continue_.setBackground(Color.lightGray);
_Load_Game_.setBackground(Color.lightGray);
_Settings_.setBackground(Color.lightGray);
_Exit_.setBackground(Color.lightGray);
MainP.setBackground(Color.gray);
_B1_.setBackground(Color.gray);
_B2_.setBackground(Color.gray);
_B3_.setBackground(Color.gray);
_B4_.setBackground(Color.gray);
MainP.add(_B1_);
MainP.add(_Continue_);
MainP.add(_B2_);
MainP.add(_Load_Game_);
MainP.add(_B3_);
MainP.add(_Settings_);
MainP.add(_B4_);
MainP.add(_Exit_);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setUndecorated(!frameBorder);
frame.pack();
frame.setMinimumSize(new Dimension(_minX, _minY));
frame.setSize(windowX, windowY);
frame.add(MainP);
frame.setVisible(true);
Finally, if I asked wrongly in any way, please tell me; so I can do better, later on, when asking questions. Hope it does not suck hours out of your life like it did me.
You need to use ActionListener. This is a method used with JButtons, and I've used it many times. JButtons are more popular and are easier to use than Buttons. JButtons are part of the swing component. Here is an example of the usage of ActionListener:
JButton button = new JButton("Example"); //Create a JButton with the text "Example"
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Code to be executed upon press goes here
}
});
I'd also like to add to #camickr's comment; Java variables should always start with a lower case letter, and never start with _. For example, JButton continue = new JButton("Continue"); would be the proper way to declare and initialize a button. Any word after the beginning word in a varable name should be capitalized. For example, JButton continueButton = new JButton("Continue"); would be the proper naming.

Create Scroll Bar for JFrame

Hi I am trying to create Scroll Bar for my JFrame. I created JPanel object and set components into JPanel. Then created a JScrollPane object for the panel. Then add the ScrollPane object to JFrame. I am not seeing any scrollbar. Also I am wondering if there is a option in JPanel that would resize the object inside Jpanel automatically according to the zoom level of the JPanel. Any help would be highly appreciated.
public class xmlottgui {
private JPanel Container;
private JFrame frmCreateXml;
private JTextField titlename;
private JLabel lbltitlename;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
xmlottgui window = new xmlottgui();
window.frmCreateXml.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public xmlottgui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Container = new JPanel();
Container.setLayout(null);
//JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frmCreateXml = new JFrame();
frmCreateXml.setTitle("Create XML");
frmCreateXml.setBounds(100, 100, 1000, 1200);
frmCreateXml.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCreateXml.getContentPane().setLayout(null);
//Create MenuBar
JMenuBar menuBar = new JMenuBar();
Container.add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmImportFromCsv = new JMenuItem("Import From Excel File");
//Add menu item Exit
JMenuItem mntmexit = new JMenuItem("Exit");
mntmexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
mnFile.add(mntmexit);
showform();
JScrollPane pane=new JScrollPane(Container,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setLayout(null);
frmCreateXml.setContentPane(pane);
frmCreateXml.getContentPane().add(pane);
}
private void showform(){
titlename = new JTextField();
titlename.setBounds(164, 27, 749, 26);
Container.add(titlename);
titlename.setColumns(10);
lbltitlename = new JLabel("Title Name");
lbltitlename.setBackground(Color.GRAY);
lbltitlename.setBounds(22, 1000, 90, 16);
Container.add(lbltitlename);
}
This:
pane.setLayout(null);
Will completely disable your JScrollPane and prevent it from working as it will prevent the JScrollPane from displaying and manipulating its view port properly. JScrollPanes have there own very special layout manager, one you never want to muck with unless you are very clever and know what you're doing. As a general rule you should almost never use null layouts.
Also this is not correct:
frmCreateXml.setContentPane(pane);
frmCreateXml.getContentPane().add(pane);
You make pane the contentPane and then add pane to itself.
AND THIS is messing you up:
frmCreateXml.getContentPane().setLayout(null);
You will want to learn about and use the layout managers as it will make your life much easier.

setMnemonic() and call a method by pressing the key

I have to run a method manually when pressing the key Alt+H
if("The key pressed==(Alt+H)"){
callMethod();
}
public void callMethod(){
//Some codes here
}
How I can actually do this in Java. Please give me a simple way to do this.
It's worth reading here about Oracle Tutorial - Enabling Keyboard Operation where it is explained in details along with sample.
Read more about on Oracle Tutorial - How to Use Key Bindings
Some example directly from the above tutorial:
//Setting the mnemonic when constructing a menu item:
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_H);
//Setting the mnemonic after creation time:
menuItem.setMnemonic(KeyEvent.VK_H);
//Setting the accelerator:
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_H, ActionEvent.ALT_MASK));
Read more here Oracle Tutorial - How to Use Buttons, Check Boxes, and Radio Buttons
Sample code: (Alt-H would click the Middle button)
JButton b2 = new JButton("Middle button", middleButtonIcon);
b2.setMnemonic(KeyEvent.VK_H);
If using menus then you can use setMnemonic(), see How to Use Menus for examples. Another option is to use Key Bindings. For example:
import java.awt.event.*;
import javax.swing.*;
public class TestKeys {
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Keys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.ALT_MASK);
Action testAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Alt-H pressed");
}
};
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "TestAction");
frame.getRootPane().getActionMap().put("TestAction", testAction);
JLabel label = new JLabel("Hit Alt-H");
label.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
frame.add(label);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Best method is to use setMnemonic() because its the the simplest.
check this article for more http://www.herongyang.com/Swing/JMenuBar-Set-Keyboard-Mnemonics-on-Menu-Items.html
private JMenu getColorMenu() {
JMenu myMenu = new JMenu("Color");
ButtonGroup myGroup = new ButtonGroup();
JRadioButtonMenuItem myItem = new JRadioButtonMenuItem("Red");
myItem.setSelected(true);
myItem.setMnemonic(KeyEvent.VK_R);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
myItem = new JRadioButtonMenuItem("Green");
myItem.setMnemonic(KeyEvent.VK_G);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
myItem = new JRadioButtonMenuItem("Blue");
myItem.setMnemonic(KeyEvent.VK_B);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
return myMenu;

How do you create an ActionListener for multiple JMenuItems?

I'm having difficulty using anonymous inner classes with actionListener. Can someone explain to me what is wrong with my code and how to use anonymous inner classes with actionListener. I'm trying to make a menu bar in one class and the action listener in the other. I ran into some difficulty when I tried using anonymous inner classes. The java website wasn't clear. Can you please explain it to me and help me fix my code.
public class Listener implements ActionListener {
HangmanView hangmanView = new HangmanView();
JFrame dialogFrame = new JFrame();
ImageIcon logo = new ImageIcon("logo.png");
public void listener1() {
hangmanView.getMenuItem().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(dialogFrame, "Developer: Joe"
, "Developer",
JOptionPane.INFORMATION_MESSAGE, logo);
}// end actionPerformed method
});
}
}
another class:
public class HangmanView {
public JMenuItem getMenuItem() {
JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
menuItem.addActionListener(new Listener());
return menuItem;
}
public JMenuBar menuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
menu.add(getMenuItem());// return here
return menuBar;
}
If you're trying to implement the listener for different JMenuItems, what I would do instead is create a custom Action class that you can use for multiple JMenuItems, as JMenuItems are a good example of when to use an Action.
private class MyAction extends AbstractAction {
String name;
public MyAction(String name, Icon icon) {
super(name, icon);
this.name = name;
}
public MyAction(String name, Icon icon, String desc,
Integer mnemonic, KeyStroke accelorator) {
super(name, icon);
putValue(Action.SHORT_DESCRIPTION, desc);
putValue(Action.MNEMONIC_KEY, mnemonic);
putValue(Action.ACCELERATOR_KEY, accelorator);
this.name = name;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (name) {
case "menu1Action":
// do something for menuItem1
break;
case "menu2Action":
// do something for menuItem2
break;
case "menu3Action":
// do something for menuItem3
break;
}
}
}
Have this class as an inner class of HangmanView. You can then create an instance of this custom Action class for each JMenuItem. Here's a example
Action menu1Action = new MyAction(
/* arg 1 */ "menu1Action",
/* arg 2 */ someIcon,
/* arg 3 */ "Some Short description of the action",
/* arg 4 */ new Integer(KeyEvent.VK_T),
/* arg 5 */ KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.CTRL_MASK));
The first argument is the name of the action. This name will be the name that you will see in the menu
The second argument is the icon that you will see in the menu next to the name.
The third argument is the Description of the menu item action
The fourth argument is the Mnemonic (i.e. Alt + T).
The fifth argument is the Accelerator (i.e. Ctrl + T).
When you add an Action to a JMenu, the title of that Action will automatically get placed as what you see in the JMenu. So all you need to do is add this custom Action to your JMenu. You don't ever have to actually create a JMenuItem at all. The Action will serve as the replacement for the JMenuItem. Just add all your MyAction objects to the JMenu.
menu.add(menu1Action);
What I have left out, is the implementation for each separate switch case in the actionPerformed. The case will be what you name the action in the constructor. Because I named the Action "menu1Action", I should have the corresponding name in the the switch case. In that case, you can do your JOptionPane or what ever else you wish to perform when that JMenuItem is clicked or accessed by keyboard.
Another great benefit of using an Action is that it can serve multiple purposes. With the same MyAction menu1Action you created, you can use the same Action for a JToolBar. Without any alteration to the above menu1Action, you could just do this:
JTooBar toolbar = new JToolBar();
toolbar.add(menu1Action);
Now in your tool bar and in your menu item, you have the same action. The tool bar will only show the icon and not the name.
Here is an example. What I do is create three different MyAction objects. One for left-alignment, one for center-alignment, and one for right-alignment. Each of these actions is used three separate times for three separate components, a menu item, a toll bar and a button
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionInterfaceDemo extends JFrame {
static JPanel buttonPanel = new JPanel();
static FlowLayout flowLayout = new FlowLayout();
public ActionInterfaceDemo(){
ImageIcon centerIcon = new ImageIcon(
ActionInterfaceDemo.class.getResource("image/centeralignment.png"));
ImageIcon rightIcon = new ImageIcon(
ActionInterfaceDemo.class.getResource("image/rightalignment.png"));
ImageIcon leftIcon = new ImageIcon(
ActionInterfaceDemo.class.getResource("image/leftalignment.png"));
Action leftAction = new MyAction("Left", leftIcon,
"Left alignment for the buttons in the panel",
new Integer(KeyEvent.VK_L),
KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
Action rightAction = new MyAction("Right", rightIcon,
"Right alignment for the buttons in the panel",
new Integer(KeyEvent.VK_R),
KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
Action centerAction = new MyAction("Center", centerIcon,
"Center alignment for the buttons in the panel",
new Integer(KeyEvent.VK_C),
KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
JMenuBar menuBar = new JMenuBar();
JMenu menuAlignment = new JMenu("Alignment");
setJMenuBar(menuBar);
menuBar.add(menuAlignment);
menuAlignment.add(leftAction);
menuAlignment.add(centerAction);
menuAlignment.add(rightAction);
JToolBar toolBar = new JToolBar("Alignment");
toolBar.setBorder(BorderFactory.createLineBorder(Color.BLUE));
toolBar.add(leftAction);
toolBar.add(centerAction);
toolBar.add(rightAction);
buttonPanel.setLayout(flowLayout);
JButton jbtLeft = new JButton(leftAction);
JButton jbtCenter = new JButton(centerAction);
JButton jbtRight = new JButton(rightAction);
buttonPanel.add(jbtLeft);
buttonPanel.add(jbtCenter);
buttonPanel.add(jbtRight);
add(toolBar, BorderLayout.EAST);
add(buttonPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ActionInterfaceDemo();
}
});
}
private class MyAction extends AbstractAction {
String name;
public MyAction(String name, Icon icon, String desc,
Integer mnemonic, KeyStroke accelorator) {
super(name, icon);
putValue(Action.SHORT_DESCRIPTION, desc);
putValue(Action.MNEMONIC_KEY, mnemonic);
putValue(Action.ACCELERATOR_KEY, accelorator);
this.name = name;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (name) {
case "Left":
flowLayout.setAlignment(FlowLayout.LEFT);
break;
case "Right":
flowLayout.setAlignment(FlowLayout.RIGHT);
break;
case "Center":
flowLayout.setAlignment(FlowLayout.CENTER);
break;
}
buttonPanel.revalidate();
}
}
}
You can press the "Left" in either the menu, the toolbar, or the button and they will produce the same result, as they are derived from the same Action.
Here are the images I used if you want to test it out
Note You don't have to use either of these exact constructors. You can create your own with different arguments. This is just a custom one I like to use.
Aslo See How to use Action tutorial
Listener, being an ActionListener through its inheritance hierarchy,
public class Listener implements ActionListener {
needs to implement an actionPerfomed(ActionEvent) method
#Override
public void actionPerformed(ActionEvent e) {
// implement it
}
However, since you seem to be adding an anonymous ActionListener, just don't have your Listener class implement ActionListener. Remove that bit.
Your object-oriented programming is all over the place. Your code in the OP looks like it's supposed to be some kind of GUI with different classes somehow working together but it's just creating new objects all over the place. There are too many reasons it doesn't work. I'd suggest you stick to something simple until you have a better grasp on how all this works.
You also got a very good suggestion in your other question that's a lot like this one but you haven't really followed it. Your code does something completely different.
Here is a very basic GUI. You have one object that has everything as fields. Everything is in one place. The containing object is the listener and decides what to do based on the event source. You should stick with a design like this until you are more comfortable with OOP.
public class HangmanView
implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new HangmanView().setFrameVisible(true);
}
});
}
private JFrame theFrame = new JFrame("Main Window");
private JPanel theContent = new JPanel();
private JMenuBar theBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private JMenuItem devMenuItem = new JMenuItem("Developer");
public HangmanView() {
assert SwingUtilities.isEventDispatchThread();
exitMenuItem.addActionListener(this);
devMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
theBar.add(fileMenu);
theBar.add(devMenuItem);
theContent.setPreferredSize(new Dimension(500, 500));
theFrame.setJMenuBar(theBar);
theFrame.setContentPane(theContent);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setLocationRelativeTo(null);
}
public void setFrameVisible(boolean vis) {
theFrame.setVisible(vis);
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == devMenuItem) {
showDevDiag();
} else if(ae.getSource() == exitMenuItem) {
systemExit();
}
}
private void showDevDiag() {
JOptionPane.showMessageDialog(
theFrame,
"Developer: Joe",
"Developer",
JOptionPane.INFORMATION_MESSAGE,
null
);
}
private void systemExit() {
System.exit(0);
}
}
if I should use anonymous class, that's what should be done:
public static void main(String args[]){
/*bla bla bla...*/
JButton button1=new JButton("button1");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae){
/*bla bla bla...*/
}
};
}
On the other hand, I always do this:
public class Class implements Runnable,ActionListener
{
private static Map<Thread,ActionEvent> THREAD_ATTRIB
=new HashMap<Thread,ActionEvent> (0);
JButton button1=new JButton("button1");
JButton button2=new JButton("button2");
//constructor
public Class(){
this.button1.addActionListener(this);
this.button2.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae){
Thread thread=new Thread(this);
THREAD_ATTRIB.put(thread,ae);
thread.start();
}
#Override
public void run(){
ActionEvent ae=THREAD_ATTRIB.get(Thread.currentThread());
if(ae!=null){
Object source=ae.getSource();
if(source.equals(this.button1){
/*bla bla bla...*/
} else if(source.equals(this.button2){
/*bla bla bla...*/
}
} else{
/*bla bla bla...*/
}
}
}

Java- How to add more textfields by clicking a button?

I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).

Categories

Resources