Dynamically add components without clicking button - java

I am adding the components dynamically at runtime on clicking the button.
But now i want to add components Dynamically without clicking button.
How can i do that..?? Here is my source code for adding a component on clicking the Button.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String[] items = new String[4];
items[0]="English";
items[1]="French";
items[2]="Spanish";
items[3]="Hindi";
JTextField jtextfield = new JTextField();
jtextfield.setPreferredSize(new Dimension(50, 20));
JButton jbutton = new JButton();
jbutton.setText("Remove");
jbutton.setPreferredSize(new Dimension(89, 23));
JLabel jlabel = new JLabel();
jlabel.setText("Text:");
jlabel.setPreferredSize(new Dimension(40, 20));
JLabel jlabel2 = new JLabel();
jlabel2.setText("Language:");
jlabel2.setPreferredSize(new Dimension(65, 20));
JComboBox jcombo = new JComboBox();
jcombo.setPreferredSize(new Dimension(80,20));
jcombo.addItem(items[0]);
jcombo.addItem(items[1]);
jcombo.addItem(items[2]);
jcombo.addItem(items[3]);
jPanel6.add(jlabel);
jPanel6.add(jtextfield);
jPanel6.add(jlabel2);
jPanel6.add(jcombo);
jPanel6.add(jbutton);
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component[]storeAllButtonInPanel = jPanel6.getComponents();
if(storeAllButtonInPanel.length!=0) {
jPanel6.remove(storeAllButtonInPanel.length-1);
jPanel6.remove(storeAllButtonInPanel.length-2);
jPanel6.remove(storeAllButtonInPanel.length-3);
jPanel6.remove(storeAllButtonInPanel.length-4);
jPanel6.remove(storeAllButtonInPanel.length-5);
jPanel6.revalidate();
validate();
repaint();
}
}
});
jPanel6.validate();
jPanel6.repaint();
}
And if i have only 2 values of Text then it also disply two rows and if 3 values then there should be only 3 rows..!! How can i do that.?

no idea what do you want, there is needed / required some control about that, as output to the GUI and by using some of Listener (as your ActionListener),
maybe (with full control) JPopupMenu, API, examples here or here

An instance of javax.swing.Timer can periodically invoke the actionPerformed() method of an ActionListener, as suggested in this example that adds and removes JLabels.

Related

Have a Button Group in Java where all buttons can be deselected?

I want to have a Button Group in which either only one option is selected or none of them are. At the moment, I can get it to have no options ticked by default, and then if one of them is ticked only one of them can be ticked, but I also want to be able to untick the button that was selected. Is this possible?
EDIT: Ideally without having a clear all button, as it would ruin the symmetry of my GUI. Also, here is my code thus far:
ButtonGroup option = new ButtonGroup();
for(int i = 0; i < n; i++) {
JCheckBox check = new JCheckBox("", false);
option.add(check);
row3b.add(check);
}
Just use the clearSelection() method of ButtonGroup :
ButtonGroup.clearSelection()
Clears the selection such that none of the buttons in the ButtonGroup
are selected.
This snippet demonstrates how you can clear selections using ButtonGroup.clearSelection():
//The buttons
JFrame frame = new JFrame("Button test");
JPanel panel = new JPanel();
JRadioButton btn1 = new JRadioButton("Button1");
JRadioButton btn2 = new JRadioButton("Button2");
JButton clearbutton = new JButton("Clear");
panel.add(btn1);
panel.add(btn2);
panel.add(clearbutton);
frame.add(panel);
frame.setVisible(true);
frame.pack();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(btn1);
btngroup.add(btn2);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
clearbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear all selections
btngroup.clearSelection();
}
});
As you can see, this creates two JRadioButtons and adds them to group then makes a button that clears selections. Really simple. Or you could create your own radio button class that allows for the unchecking of the button, which is also doable relatively easily.

Add new fields with press of a button

I´m creating a program in NetBeans where the user can create their own CSV-file. I've made a GUI. When I press the button, I want a new JLabel and a new JTextField to appear underneath the existing ones, for as many times as the button is pressed. How do I do that?
I've done something similiar and I'm using a JPanel with GroupLayout to solve this problem and that's my code:
EDIT - Your question aroused my interest and I've changed my code to your needs (of course only the basic, you will have to improve it)
Global variables
private GroupLayout m_layout;
private SequentialGroup m_verticalSg;
private ArrayList<Component> m_labelList;
private ArrayList<Component> m_textFieldList;
private ParallelGroup m_horizontalPgLabels;
private ParallelGroup m_horizontalPgTextfields;
Method createLayout()
Creates the layout for your panel which should contain the label & textfield components
private void createLayout()
{
m_layout = new GroupLayout(YOUR_PANEL);
YOUR_PANEL.setLayout(m_layout);
//This SequentialGroup is used for the VerticalGroup
m_verticalSg = m_layout.createSequentialGroup();
m_verticalSg.addContainerGap();
//Two ParallelGroups are used. One for all labels and the other one for all textfields
m_horizontalPgLabels = m_layout.createParallelGroup(GroupLayout.Alignment.LEADING);
m_horizontalPgTextfields = m_layout.createParallelGroup(GroupLayout.Alignment.LEADING);
//These component lists are used for linkSize() -> Equalize components width
m_labelList = new ArrayList<>();
m_textFieldList = new ArrayList<>();
m_layout.setHorizontalGroup(m_layout.createParallelGroup()
.addGroup(m_layout.createSequentialGroup()
.addContainerGap()
.addGroup(m_horizontalPgLabels)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) //Create gap between horizontal groups
.addGroup(m_horizontalPgTextfields)
.addContainerGap()));
m_layout.setVerticalGroup(m_layout.createParallelGroup().addGroup(m_verticalSg.addContainerGap()));
}
Method addNewRow()
Call this method from your button click event
private void addNewRow()
{
if(m_layout == null)
createLayout();
Dimension dimLabel = new Dimension(100, 15);
Dimension dimTextfield = new Dimension(200, 20);
//Create a new label
JLabel lbl = new JLabel();
lbl.setText("Your text");
lbl.setIcon(null/*Your icon*/);
lbl.setSize(dimLabel);
lbl.setPreferredSize(dimLabel);
//Create a new textfield
JTextField txtField = new JTextField();
txtField.setSize(dimTextfield);
txtField.setPreferredSize(dimTextfield);
//Add components to arrays and increase index
m_labelList.add(lbl);
m_textFieldList.add(txtField);
//Create new ParallelGroup for the vertical SequentialGroup
ParallelGroup newVerticalParallelGroup = m_layout.createParallelGroup(GroupLayout.Alignment.LEADING);
newVerticalParallelGroup.addComponent(lbl);
newVerticalParallelGroup.addComponent(txtField);
m_verticalSg.addGroup(newVerticalParallelGroup);
m_verticalSg.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
//Add the new label to the horizontal label group
m_horizontalPgLabels.addComponent(lbl, GroupLayout.Alignment.CENTER);
//Add the new textfield to the horizontal textfield group
m_horizontalPgTextfields.addComponent(txtField);
m_layout.linkSize(SwingConstants.HORIZONTAL, m_labelList.toArray(new Component[m_labelList.size()]));
m_layout.linkSize(SwingConstants.HORIZONTAL, m_textFieldList.toArray(new Component[m_textFieldList.size()]));
}
The last step is to add an ActionListener to your button to call the method addNewRow().
jButton1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
addNewRow();
}
});
Feel free to ask me if something is unclear.

How to update JTextfield after click SAVE button

I have a main frame : JFrame>contentFrame>ScrollPane>BigPanel>panel_1T
private JPanel contentPane;
private JPanel BigPanel;
private JPanel panel_1T;
In panel_1T, I have put a FOOD button WITH its actionListener:
JButton button_19 = new JButton("FOOD");
button_19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
});
panel_1T.setLayout(new GridLayout(0, 2, 0, 0));
panel_1T.add(button_19);
When user click FOOD button, new JFrame in newFoodUI class will be shown.:
JFrame>contentPane>panel>tabbedPane>panel_3>panel_5
In panel_5, I put a JTextField:
public static JTextField textField_3;
textField_3 = new JTextField();
panel_5.add(textField_3, "9, 4, fill, default");
textField_3.setColumns(10);
User will write some text into textField_3. Then user click SAVE button in panel_3, it will perform this:
JButton button_4 = new JButton("SAVE");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setContentPane(contentPane);
panel_3.revalidate();
panel_3.repaint();
panel_3.updateUI();
panel_5.revalidate();
panel_5.repaint();
panel_5.updateUI();
contentPane.revalidate();
contentPane.repaint();
JOptionPane.showMessageDialog(null, "Saved !");
}
});
button_4.setBounds(873, 396, 75, 33);
contentPane.add(button_4);
}
The result is, when I click SAVE button and close the Frame in newFoodUI, I will reopen back by click the FOOD button to check whether the text I wrote has been saved or not. But its not saving the text I wrote.
You have to save the value from the textfeld textField_3.getText() and set this value manually to textfeld when showing textField_3.setText(value). So you have to keep your value in your project or store persistent somewhere.
There are a couple of things to fix here and I will not give you complete code but I will point out some errors. First let's consider your button_19 listener
public void actionPerformed(ActionEvent ae) {
newFoodUI nf = new newFoodUI();//Open other class
nf.setVisible(true);
nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
When this is performed, it creates a totally new object of newFoodUI and gives it no parameters. So how could this frame know about anything that happened before its creation if you give it nothing? Additionally, you explicitly say DISPOSE_ON_CLOSE, when you could use HIDE_ON_CLOSE if you wish to reuse it.
Then in your JButton button_4 = new JButton("SAVE"); listener you want to save the data in the text field, but your implementation does nothing to the text field. You should, for example, get the text from textField_3 and write it to a file or send back to the first JFrame.
Then there is the issue of using multiple JFrames in the first place.

Unable to add text to JTextArea in Java from another function

I made a simple program in Java that contains only one text area and a button. The button is suppose to add a "text". However, it doesn't work for me.
On a side note: I'm trying to keep my functions as short as possible. (I don't want a function with too many line of codes)
First, I create the JFrame
private static void createFrame()
{
//Build JFrame
JFrame frame = new JFrame("Text Frame");
frame.setLayout(null);
frame.setSize(500,400);
Container contentPane = frame.getContentPane();
contentPane.add(textScrollPane());
contentPane.add(buttonAddText());
//Set Frame Visible
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Then the TextArea and the Scrollpane (for adding scrollbar)
private static JTextArea textArea()
{
JTextArea output = new JTextArea();
output.setLineWrap(true); // Text return to line, so no horizontal scrollbar
output.setForeground(Color.BLACK);
output.setBackground(Color.WHITE);
return output;
}
private static JScrollPane textScrollPane()
{
JScrollPane scrollPane2 = new JScrollPane(textArea());
scrollPane2.setBounds(0, 0, 490, 250);
return scrollPane2;
}
And finally, the button
private static JButton buttonAddText()
{
JButton testbutton = new JButton("TEST");
testbutton.setBounds(20, 280, 138, 36);
testbutton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
//action listener here
textArea().insert("TEXT",0);
System.out.println("Button Tested!");
}
});
return testbutton;
}
When I click on the button, it doesn't do anything.
I just want a text to be added in the JTextArea. Did I forget something?
textArea() is returning a new JTextArea everytime it is called. Therefore your buttonAddText() function is calling textArea() and adding text to a newly created text area that is not contained in the scroll pane.
You need to pass a reference of the text area to the textScrollPane() and the buttonAddText() functions.
Something like this would work:
JTextArea jta = textArea();
contentPane.add(textScrollPane(jta));
contentPane.add(buttonAddText(jta));
Change textScrollPane() and buttonAddText() so that they accept a JTextArea parameter and don't call textArea() in these functions anymore to create new text areas. Instead use the JTextArea object which is passed into the functions.

Java JmenuItem do something when clicked not working

I am currently trying to make a GUI with a menu that has 2 options you can select from. One being "Default Settings" and one being "Custom Settings." When you click on either one, it will take you to the new jPanel that will display the proper windows, text boxes, etc for that panel. However, I cannot seem to get the mouseClicked action to actually switch between the panels. As a test, I have a simple jLabel on each panel that says "Default" for the default panel and "custom" for the custom panel, and each menu item, when clicked respectively, should switch between them. Here is my current code:
frmLegitServerAdder = new JFrame();
frmLegitServerAdder.setTitle("Legit Server Adder 5 Million");
frmLegitServerAdder.setBounds(100, 100, 546, 468);
frmLegitServerAdder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frmLegitServerAdder.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Settings");
menuBar.add(mnNewMenu);
JMenuItem menuItemDefaultSettings = new JMenuItem("Default Settings");
mnNewMenu.add(menuItemDefaultSettings);
JMenuItem menuItemCustomSettings = new JMenuItem("Custom Logon Settings");
mnNewMenu.add(menuItemCustomSettings);
frmLegitServerAdder.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel defaultSettingsPanel = new JPanel();
frmLegitServerAdder.getContentPane().add(defaultSettingsPanel, "name_416522810155567");
defaultSettingsPanel.setLayout(null);
JLabel lblDefaultArea = new JLabel("Default Area");
lblDefaultArea.setBounds(217, 11, 90, 14);
defaultSettingsPanel.add(lblDefaultArea);
final JPanel customSettingsPanel = new JPanel();
frmLegitServerAdder.getContentPane().add(customSettingsPanel, "name_416549691176064");
customSettingsPanel.setLayout(null);
JLabel lblCustomArea = new JLabel("Custom Area");
lblCustomArea.setBounds(235, 21, 46, 14);
customSettingsPanel.add(lblCustomArea);
menuItemDefaultSettings.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
defaultSettingsPanel.setVisible(true);
customSettingsPanel.setVisible(false);
}
});
menuItemCustomSettings.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
defaultSettingsPanel.setVisible(false);
customSettingsPanel.setVisible(true);
}
});
The code runs and the GUI displays just fine, but nothing actually happens when I click on either menu items, as it should. Any ideas?
You should NOT be using a MouseListener. Instead you should be adding an ActionListener to the menu item. Read the section from the Swing tutorial on How to Use Menus for more information.
You should be using a CardLayout when you want to swap components. See How to Use Card Layout from the same tutorial.
You need ActionListener
menuItemDefaultSettings.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
defaultSettingsPanel.setVisible(true);
customSettingsPanel.setVisible(false);
}
});
Hope this helps.

Categories

Resources