Using an event to do something in another class in Java - java

based on my understanding,
`list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
}}
will do something when something in the list was selected, and
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
do something when the button have been pushed.
I want to write a code to delete the selected item from one list and add it to another one.
I can't use Jlist methods because it is not in the scope of button.
I am not sure how to do it. and I can't find something that solve my problem on net or books.
Thank you so much
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JList;
import java.awt.GridLayout;
import javax.swing.JSplitPane;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JSeparator;
import java.awt.Panel;
import java.awt.List;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.Font;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. This is the constructor for this Window class.
* All of the code here will be executed as soon as a Window object is made.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame. This is where Window Builder
* will generate its code.
*/
public void initialize() {
//creates an array for the list of components
String pclist[]={"case","moderboard","CPU","GPU","PSU","RAM","HDD"};
frame = new JFrame();
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmLoad = new JMenuItem("Load");
mnFile.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
frame.getContentPane().setLayout(null);
JButton button = new JButton(">>");
button.setBounds(244, 170, 82, 36);
button.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button);
JButton button_1 = new JButton("<<");
button_1.setBounds(244, 219, 82, 36);
button_1.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button_1);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 205, 493);
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
JList list = new JList();// implements ActionListener;
list.setBounds(0, 0, 205, 493);
list.setListData(pclist); //populate the Jlist
list.setFont(new Font("Tahoma", Font.BOLD, 18));
panel.add(list);
JPanel panel_1 = new JPanel();
panel_1.setBounds(358, 0, 212, 493);
panel_1.setBackground(Color.WHITE);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JList list_1 = new JList();
list_1.setBounds(203, 0, -200, 480);
list_1.setSelectedIndex(0);
list_1.setFont(new Font("Tahoma", Font.BOLD, 18));
panel_1.add(list_1);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//list_1.addElement("hi");
System.out.println("hoi");
}
});
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent arg0) {
}});
list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
}
}
);
}
}

Start by making your JLists instance variables
public class Window {
private JFrame frame;
private JList list;
private JList list_1;
Make sure you're initialising the instance variables and not creating new local variables...
//JList list = new JList();// implements ActionListener;
list = new JList();// implements ActionListener;
//...
panel.add(list);
//JList list_1 = new JList();
list_1 = new JList();
//...
panel_1.add(list_1);
This now means that the JLists are accessible from within the context of an instance of the class...
Then in your ActionListeners, you can simple do something like...
Object selected = list.getSelectedValue();
or...
int index = list.getSelectedIndex();
You can then use these values to modify the state of the underlying ListModel...if it supports those operations...

Related

add from one jlist to another

I have been doing research on here and have been searching for a solution to the problem. I am new to java so I don't know all of the syntax. I am trying to get my code to transfer items from one jlist to another using the buttons in-between the jlists. The left list has the items to begin with. The code is suppose to move items from the left list to the right list with the add button; also suppose to move whatever items we added to the right list back to the left list with the remove button. My code adds the item from left list to right list but it does not hold the item added. The next item I try to add just replaces the old item. Can anyone help me out please? Below is the entire code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
initialize();
}
public void initialize() {
//Creating the Panel for Menu Bar
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 23);
frame.getContentPane().add(panel);
panel.setLayout(new BorderLayout(0, 0));
//Creating the Menu File Bar
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu file = new JMenu("File");
JMenuItem load = new JMenuItem("Load");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
file.add(load);
file.add(save);
file.add(exit);
bar.add(file);
//Populate Left List with part names
final DefaultListModel parts = new DefaultListModel();
parts.addElement("Case");
parts.addElement("Motherboard");
parts.addElement("CPU");
parts.addElement("GPU");
parts.addElement("PSU");
parts.addElement("RAM");
parts.addElement("HDD");
final JList leftList = new JList(parts);
leftList.setBounds(10, 26, 142, 224);
frame.getContentPane().add(leftList);
//create right list
final DefaultListModel partSelected = new DefaultListModel();
final JList rightList = new JList();
rightList.setBounds(282, 26, 142, 224);
frame.getContentPane().add(rightList);
//add event to the button to move items from left list to right list
JButton btnNewButton = new JButton(">>");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : leftList.getSelectedValuesList()) {
partSelected.addElement(selectedValue);
parts.removeElement(selectedValue);
int iSelected = leftList.getSelectedIndex();
if (iSelected == -1) {
return;
}
}
}
});
btnNewButton.setBounds(172, 86, 89, 23);
frame.getContentPane().add(btnNewButton);
//Remove Button
JButton remove = new JButton("<<");
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : rightList.getSelectedValuesList()) {
parts.addElement(selectedValue);
int selected = rightList.getSelectedIndex();
if (selected == -1) {
return;
}
partSelected.removeElement(selectedValue);
}
}
});
remove.setBounds(172, 140, 89, 23);
frame.getContentPane().add(remove);
}
}
#Prob1em I've updated your code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Window {
private final JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Window window = new Window();
window.frame.setVisible(true);
});
}
public Window() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
initialize();
}
public void initialize() {
//Creating the Panel for Menu Bar
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 23);
frame.getContentPane().add(panel);
panel.setLayout(new BorderLayout(0, 0));
//Creating the Menu File Bar
JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);
JMenu file = new JMenu("File");
JMenuItem load = new JMenuItem("Load");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
file.add(load);
file.add(save);
file.add(exit);
bar.add(file);
//Populate Left List with part names
final DefaultListModel parts = new DefaultListModel();
parts.addElement("Case");
parts.addElement("Motherboard");
parts.addElement("CPU");
parts.addElement("GPU");
parts.addElement("PSU");
parts.addElement("RAM");
parts.addElement("HDD");
final JList leftList = new JList(parts);
leftList.setBounds(10, 26, 142, 224);
frame.getContentPane().add(leftList);
//create right list
final DefaultListModel partSelected = new DefaultListModel();
final JList rightList = new JList(partSelected);
rightList.setBounds(282, 26, 142, 224);
frame.getContentPane().add(rightList);
//add event to the button to move items from left list to right list
JButton btnNewButton = new JButton(">>");
btnNewButton.addActionListener((ActionEvent arg0) -> {
// rightList.setListData((Vector) leftList.getSelectedValue());
for (Object selectedValue : leftList.getSelectedValuesList()) {
partSelected.addElement(selectedValue);
parts.removeElement(selectedValue);
int iSelected = leftList.getSelectedIndex();
if (iSelected == -1) {
return;
}
}
});
btnNewButton.setBounds(172, 86, 89, 23);
frame.getContentPane().add(btnNewButton);
//Remove Button
JButton remove = new JButton("<<");
remove.addActionListener((ActionEvent arg0) -> {
// rightList.setListData(leftList.getSelectedValues());
for (Object selectedValue : rightList.getSelectedValuesList()) {
parts.addElement(selectedValue);
partSelected.removeElement(selectedValue);
int selected = rightList.getSelectedIndex();
if (selected == -1) {
return;
}
}
});
remove.setBounds(172, 140, 89, 23);
frame.getContentPane().add(remove);
}
}
btw why did you write rightList.setListData(leftList.getSelectedValues()) and its also a deprecated method in Java 8 please follow proper naming conventions while declaring variables though I haven't changed them in this code, the event handling functions are as per Java 8 lambda expression,
Hope this helps

Can not save state of static checkbox

I have created a small settings menu, which save the state of checboxes by clicking save and quit and of course forget the state by clicking cancel.
I need a reference to the checkboxes, so I have to use static. But when I use it, the save state function won't work correctly anymore...Why? :(
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.prefs.Preferences;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class SettingsGui extends JPanel {
static Preferences PREFS = Preferences.userNodeForPackage(SettingsGui.class);
JCheckBox testAllPagesHaveSameRotation;
JCheckBox testAllPagesHaveSameSize;
JCheckBox testContent;
JTabbedPane tabbedPane;
ButtonGroup buttonGroup;
public SettingsGui() {
setPreferredSize(new Dimension(500, 500));
setLayout(new BorderLayout());
tabbedPane = new JTabbedPane(SwingConstants.LEFT, JTabbedPane.WRAP_TAB_LAYOUT);
tabbedPane.setFont(new Font("Arial", Font.BOLD, 13));
JPanel pdfCheckOptions = new JPanel(new GridLayout(3, 1));
testAllPagesHaveSameRotation = new JCheckBox("testAllPagesHaveSameRotation");
testAllPagesHaveSameRotation.setFont(new Font("Arial", Font.PLAIN, 15));
testAllPagesHaveSameSize = new JCheckBox("All pages have same size");
testAllPagesHaveSameSize.setFont(new Font("Arial", Font.PLAIN, 15));
testContent = new JCheckBox("Content");
testContent.setFont(new Font("Arial", Font.PLAIN, 15));
tabbedPane.addTab("Check Settings", pdfCheckOptions);
pdfCheckOptions.add(testAllPagesHaveSameRotation);
pdfCheckOptions.add(testAllPagesHaveSameSize);
pdfCheckOptions.add(testContent);
add(tabbedPane);
load();
}
public void store() {
PREFS.putBoolean("test1", testAllPagesHaveSameRotation.isSelected());
PREFS.putBoolean("test2", testAllPagesHaveSameSize.isSelected());
PREFS.putBoolean("test3", testContent.isSelected());
public void load() {
testAllPagesHaveSameRotation.setSelected(PREFS.getBoolean("test1", false));
testAllPagesHaveSameSize.setSelected(PREFS.getBoolean("test2", false));
testContent.setSelected(PREFS.getBoolean("test3", false));
}
class Gui {
JDialog settingsDialog;
SettingsGui content;
JButton saveButton;
JButton cancelButton;
JPanel buttonPanel;
public Gui() {
content = new SettingsGui();
settingsDialog = new JDialog(settingsDialog, "Settings");
settingsDialog.setContentPane(content);
settingsDialog.setLocationRelativeTo(null);
settingsDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
settingsDialog.pack();
settingsDialog.setVisible(true);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
saveButton = new JButton("Save and Quit");
cancelButton = new JButton("Cancel");
buttonPanel.add(saveButton);
buttonPanel.add(cancelButton);
settingsDialog.add(buttonPanel, BorderLayout.SOUTH);
saveButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
content.store();
settingsDialog.dispose();
}
});
cancelButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PREFS.putBoolean("test1", testAllPagesHaveSameRotation.isSelected());
PREFS.putBoolean("test2", testAllPagesHaveSameSize.isSelected());
PREFS.putBoolean("test3", testContent.isSelected());
settingsDialog.dispose();
}
});
}
}
public static void main(String[] args) {
new SettingsGui().new Gui();
}
}

Eclipse WindowBuilder (swing) - some components not accessible in code?

Edit - #Heuster linked another question that answers this.
I just found out about WindowBuilder and I'm making a simple chat client using it to teach myself. Right now I've got the basic chat frame done, but only some of the components that I've added are accessible in the code. Specifically, I can't access my input JTextArea, taInput. Is there something I need to do to be able to reference it (to get the text in it for sending, etc.)?
Here's a picture of the Design view:
And here's a the generated code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
public class frame extends JFrame
{
private JPanel contentPane;
private JButton btnSend;
private JTextArea taDisplay;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame frame = new frame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frame()
{
setResizable(false);
setTitle("Client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 440, 316);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmConnect = new JMenuItem("Connect...");
mnFile.add(mntmConnect);
JMenuItem mntmSaveChatLog = new JMenuItem("Save chat log...");
mnFile.add(mntmSaveChatLog);
JMenuItem mntmSettings = new JMenuItem("Settings...");
mnFile.add(mntmSettings);
JMenuItem mntmClose = new JMenuItem("Close");
mnFile.add(mntmClose);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnView = new JMenu("View");
menuBar.add(mnView);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
btnSend = new JButton("Send");
btnSend.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
taDisplay.append("Send clicked.\n");
}
});
btnSend.setBounds(314, 197, 100, 50);
panel.add(btnSend);
taDisplay = new JTextArea();
taDisplay.setLineWrap(true);
taDisplay.setEditable(false);
taDisplay.setBounds(10, 11, 404, 180);
panel.add(taDisplay);
JScrollPane spInput = new JScrollPane();
spInput.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
spInput.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spInput.setBounds(10, 197, 294, 49);
panel.add(spInput);
JTextArea taInput = new JTextArea();
taInput.setLineWrap(true);
spInput.setViewportView(taInput);
}
}
From the design tab you could right click on the item (taInput) then click rename on the context menu, in the diaog, at the right of the name there where 2 buttons, clic on the (f) button (field) and then ok.

Java UIManager - Change ComponentsStyle

I want to change my componentstyle by using UIManager.
For example:
I click on a Button and the Button foreground changes from black to green. The same for a JCheckbox.....
In my example the changes just work for the Button.gradient.... I get no update for Button.foreground and no update for the JCheckbox!
Here my UIManagerClass:
package components;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
public class OwnUiManager {
ButtonDemo Bd;
OwnUiManager(ButtonDemo aThis) {
Bd = aThis;
}
public void setNormal() {
ArrayList<Object> gradients = new ArrayList();
gradients.add(0.3);
gradients.add(0.0);
gradients.add(new Color(221, 232, 243));
gradients.add(new Color(255, 255, 255));
gradients.add(new Color(184, 207, 229));
javax.swing.UIManager.put("RadioButton.background", Color.PINK);
javax.swing.UIManager.put("Button.gradient", gradients);
javax.swing.UIManager.put("Button.foreground", Color.PINK);
SwingUtilities.updateComponentTreeUI(Bd);
}
public void setNightVision() {
System.out.println("Tes");
ArrayList<Object> gradients = new ArrayList();
gradients.add(0.18f);
gradients.add(0.17f);
gradients.add(Color.BLACK);
gradients.add(Color.DARK_GRAY);
gradients.add(Color.DARK_GRAY);
javax.swing.UIManager.put("RadioButton.background", Color.GRAY);
javax.swing.UIManager.put("Button.gradient", gradients);
javax.swing.UIManager.put("Button.foreground", Color.red);
SwingUtilities.updateComponentTreeUI(Bd);
}
}
and here my Buttondemo/Main-Class:
package components;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ButtonDemo extends JPanel
implements ActionListener {
protected JButton b1,b2;
private JRadioButton b3;
public ButtonDemo() {
b1 = new JButton("ON");
b1.addActionListener(this);
add(b1);
b2 = new JButton("OFF");
b2.addActionListener(this);
add(b2);
//For Testing the Style
b3=new JRadioButton("Test");
add(b3);
}
public void actionPerformed(ActionEvent e) {
OwnUiManager test = new OwnUiManager(this);
if (e.getSource().equals(b1)) {
test.setNormal();
} else {
test.setNightVision();
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonDemo newContentPane = new ButtonDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
JCheckBox / JRadioButton has Icon
have to change own Icon to concrete JCheckBox / JRadioButton or put then to the UIManager, then apply for whole JVM instance
for more infos have to check UIManager Defaults and Key Bindings by camickr
most of your potential issues is descibed in Creating a custom button in Java with JButton

Dynamically adding textboxes and JSlider from a different class

I want to add textfields dynamically on the click of a button but the value to be fetched and the button are in one class and the panel where i want to add the textboxes and sliders adjacent to the are in a different class. Code is -
public class TipSplitting extends JPanel
JLabel lblNoOfGuests = new JLabel("No. Of guests");
lblNoOfGuests.setBounds(10, 26, 95, 14);
add(lblNoOfGuests);
private JTextField noofguests = new JTextField();
noofguests.setBounds(179, 23, 86, 20);
add(noofguests);
noofguests.setColumns(10);
JButton btnTiptailoring = new JButton("TipTailoring");
btnTiptailoring.setBounds(117, 286, 89, 23);
add(btnTiptailoring);
public class TipTailoring extends JPanel {}
In this class I need to create the text fields dynamically according to the no. entered. In the variable noofguests and the click of the button in the previous class.
I can't really see what the problem, but here some simple demo code of what you describe.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestDynamicallyAddedTextFields {
private void initUI() {
JFrame frame = new JFrame(TestDynamicallyAddedTextFields.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel textfieldContainerPanel = new JPanel();
textfieldContainerPanel.setLayout(new GridBagLayout());
JLabel nrOfGuests = new JLabel("Nr. of guests");
final JFormattedTextField textfield = new JFormattedTextField();
textfield.setValue(Integer.valueOf(1));
textfield.setColumns(10);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textfield.getValue() != null) {
addTextFieldsToPanel((Integer) textfield.getValue(), textfieldContainerPanel);
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
panel.add(nrOfGuests);
panel.add(textfield);
panel.add(add);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textfieldContainerPanel));
frame.setSize(300, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void addTextFieldsToPanel(Integer value, JPanel textfieldContainerPanel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
for (int i = 0; i < value; i++) {
textfieldContainerPanel.add(new JTextField(20), gbc);
}
textfieldContainerPanel.revalidate();
textfieldContainerPanel.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestDynamicallyAddedTextFields().initUI();
}
});
}
}
And the result:

Categories

Resources