how can i add components dynamically in a jpanel?
I am having add button when i click the button the components should be added to the JPanel.
my question is that adding a textfield and button to jpanel when i click on the add button the user can click on the add button any number of times according to that i have to add them to the jpanel. i have added to scrollerpane to my jpanel,and jpanel layout manager is set to null.
Just as you always do, except that you have to call:
panel.revalidate();
when you are done, since the container is already realized.
Use an ActionListener, you can use an anonymous class like this:
JPanel myJPanel = new JPanel();
...
b = new Button("Add Component");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel someLabel = new JLabel("Some new Label");
myJPanel.add(someLabel);
myJPanel.revalidate();
}
});
Related
I am trying the build a GUI, I have a set of radio buttons and I want a slider to show only when a specific radio button is pressed
I have set the visibility of the panel which contains the slider to false, but I can't reach that panel outside of AddVehicleDialog class (because it is a local variable of that class) and I need access for it in MyActionListener class.
I tried using getRootPane() to get the panel which the slider was added to, but it returned null.
//AddVehicleDialog.java class
public class AddVehicleDialog extends JDialog {
// All of the addVehicleDialog buttons, radio buttons and sliders
JButton okButton, cancelButton;
static JRadioButton redButton, grnButton, whtButton, svrButton;
static JRadioButton benzineCar, solarCar, bikeRadButton, carriageRadButton;
JSlider gearsSlider;
public AddVehicleDialog() {
setTitle("Add a vehicle to the city");
setLayout(new BorderLayout());
setSize(550, 300);
setResizable(false);
setLocationRelativeTo(null);
setModal(true);
// OK & Cancel buttons & radio buttons
addVehicleDialogButtons();
}
//bike's gears slider - part of addVehicleDialogButtons() method;
gearsSlider = new JSlider(0, 10);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
JLabel gearsLabel = new JLabel("Choose bike's gears");
gearsLabel.setHorizontalAlignment(JLabel.CENTER);
gearsLabel.setVerticalAlignment(JLabel.CENTER);
centerPanel.add(gearsLabel);
gearsSlider.setMajorTickSpacing(2);
gearsSlider.setMinorTickSpacing(1);
gearsSlider.setPaintTicks(true);
gearsSlider.setPaintLabels(true);
gearsSlider.setExtent(0);
centerPanel.add(gearsSlider,BorderLayout.SOUTH);
centerPanel.setVisible(false);
this.add(centerPanel,BorderLayout.CENTER);
//MyActionListener class is in a different file from centerPanel component
public class MyActionListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
.
.
.
case "OK":
if (AddVehicleDialog.bikeRadButton.isSelected()) {
//this is what i want to do
centerPanel.setVisible(true);
}
I know I can't reach centerPanel, because it is a local variable of AddVehicleDialog class.
I've made the gearsSlider static so I could reach him in MyActionListener class
I don't think it is a good practice to put centerPanel as static, but I can't think of other way to reach this specific panel outside of the class.
I hope it is understandable enough. If more clarification is needed, please tell and I'll provide.
The panel when visibility set to false:
The way I want the panel to look when I select Bike radio button.
public class Create_JFrame extends JFrame{
public Create_JFrame(){
//Create a Frame
JFrame Frame = new JFrame("Bla-Bla");
JPanel Panel_1 = new JPanel();
JPanel Panel_2 = new JPanel();
JButton Option_1 = new JButton("Option-1");
//Layout management for Panels
Frame.getContentPane().add(BorderLayout.WEST, Panel_1);
//Add button to Panel
Panel_1.add(Option_1);
//Registering Listeners for all my buttons
Option_1.addActionListener(new ListenerForRadioButton(Panel_2));
//Make the frame visible
Frame.setSize(500, 300);
Frame.setVisible(true);
}//end of Main
}//end of Class
public class ListenerForRadioButton implements ActionListener{
JPanel Panel_2;
JButton browse = new JButton("Browse");
//Constructor, will be used to get parameters from Parent methods
public ListenerForRadioButton(JPanel Panel){
Panel_2 = Panel;
}
//Overridden function, will be used for calling my 'core code' when user clicks on button.
public void actionPerformed(ActionEvent event){
Panel_2.add(browse);
System.out.println("My listener is called");
}//end of method
}//end of class
Problem Statement:
I have 2 JPanel components in a a given JFrame. Panel_1 is having a Option_1 JButton. When user clicks on that I am expecting my code to add a JButton 'browse' in Panel_2 at runtime.
Runtime Output:
System is not adding any JButton in Panel_2. However, I see my debug message in output, indicating that system was successful in identifying user's click action on 'option-1'.
Question:
Why is JPanel not adding any component at Runtime?
Panel_2.add(browse);
Panel_2.revalidate();
adding a 'revalidate' will solve the problem.
There are some reasons. but:
usually it's because of using unsuitable LayoutManager.
sometimes it's because of adding the JPanel to it's root component in worng way. which any operation (add, remove,...) works but is not visible.
you must refresh the view when you make some changes on it, like adding or removing components to/from it.
try to use Panel_2.revalidate() to refresh.
if it doesn't work properly use it with Panel_2.repaint() method.
see Java Swing revalidate() vs repaint()
see Difference between validate(), revalidate() and invalidate() in Swing GUI
using setSize twice for your jframe is another way.
Frame.setSize(498, 300); then Frame.setSize(500, 300);
I have a JTabbedPane with 5 tabs in it. I also got 3 other buttons in same JFrame where my JTabbedPane is added. I want to make the user able move to particular tab when a particular button is clicked. Here is the image example
Now for example if user clicks Button 1 then tab One should be opened and similarly when button 2 is clicked then tab Two should be opened and so for third one.
Here is my code to add these JTabbedPane and buttons.
public class TabsAndButtons
{
public TabsAndButtons()
{
JTabbedPane tabsPane = new JTabbedPane();
tabsPane.add("One", new JPanel());
tabsPane.add("Two", new JPanel());
tabsPane.add("Three", new JPanel());
tabsPane.add("Four", new JPanel());
tabsPane.add("Five", new JPanel());
JPanel Panel = new JPanel();
Panel.add(tabsPane);
JButton Button1 = new JButton("Button 1");
Panel.add(Button1);
JButton Button2 = new JButton("Button 2");
Panel.add(Button2);
JButton Button3 = new JButton("Button 3");
Panel.add(Button3);
JFrame MainFrame = new JFrame("JTabbedPane and Buttons");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(Panel );
MainFrame.pack();
MainFrame.setVisible(true);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new TabsAndButtons();
});
}
}
The actual purpose of such action is very lengthy and has a lot details which will make the question dull so I am asking the main task where I stucked. Thanks for your kind support and time.
Use the method button.addActionListener() to execute code when a button is clicked. The code that you want to execute is probablytabsPane. setSelectedIndex(i)wherei` is the index of the tab that you want to show.
You might also want to move the JTabbedPane tabsPane into a member variable, or mark it with final, to make sure that it can be accessed from within the action listener.
Add an ActionListener to each of the buttons. Then in the ActionListener you can invoke the setSelected(...) method of the tabbed pane.
Read the section from the Swing tutorial on How to Write an ActionListener for more information and examples.
Also, variable name should NOT start with an upper case character.
Try in the EventListener for the Buttons the Method setSelectedIndex(int index) on your JTabbedPane.
The Referenz: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTabbedPane.html#setSelectedIndex%28int%29
I have a program which creates 2 Panels and then places a label and two buttons in them. The label is set to invisible setVisible(false) and then the two buttons are added and the frame is packed. When i click the first button, the label is shown, setVisible(true), and the seccond one hides it again, setVisible(false). When i click each button, they move to fill the space of the label as it hides, and move again to get out of the way of the label as it is shown. I want to stop this from happening and have the buttons stay in the same place even when the label is hidden.
Here is the code:
public class MainFrame extends JFrame{
public JLabel statusLabel;
public JButton show;
public JButton hide;
public MainFrame(){
super("MagicLabel");
JPanel topPanel = new JPanel(); //Create Top Panel
statusLabel = new JLabel(""); //Init label
statusLabel.setVisible(false); //Hide label at startup
topPanel.setSize(400, 150); //Set the size of the panel, Doesn't work
topPanel.add(statusLabel); //Add label to panel
JPanel middlePanel = new JPanel(); //Create Middle Panel
show= new JButton("Show"); //Create show button
hide= new JButton("Hide"); //Create hide button
middlePanel.setSize(400, 50); //Set the size of the panel, Doesn't work
middlePanel.add(show); //Add show button
middlePanel.add(hide); //Add hide button
this.add(topPanel, "North"); //Add Top Panel to North
this.add(middlePanel, "Center"); //Add Middle Panel to Center
addActionListeners(); //void:adds action listeners to buttons
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 512, 400);
this.setPreferredSize(new Dimension(400,200)); //Set size of frame, Does work
this.pack();
this.setVisible(true);
}
public void animateInstall(boolean var0){ //Void to show and hide label from action listeners
statusLabel.setVisible(var0);
sendWorkingMessage("Boo!");
}
public void sendWorkingMessage(String message){ //Void to set text of label
this.statusLabel.setForeground(new Color(225, 225, 0));
this.statusLabel.setText(message);
}
void addActionListeners(){
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(true);
}
});
hide.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(false);
}
});
}
this.setPreferredSize(new Dimension(400,200));
this.setMinimumSize(new Dimension(400,200));
So pack() cannot interfere.
Use CardLayout. Add the JLabel and empty JPanel. Instead of seting it visible/invisible swap the cards showing the JLabel or the JPanel when necesary.
Extending JFrame is not advisable, better extend JPanel put all your components inside and then add it to a JFrame
You need to learn how to use SwingUtilities.invokeLater(): See example how your should look like
You need to learn about Layout: Tutorial
Very dumb and easy approach in your code would be:
this.statusLabel.setForeground(bgColor); //background color
this.statusLabel.setText(" "); //some number of characters
By default for you frame you are using BorderLayout. You can try to have like:
this.add(topPanel, BorderLayout.NORTH); //Add Top Panel to North
this.add(middlePanel, BorderLayout.SOUTH); //Add Middle Panel to South
rather than at center.
Or you can create an intermediate container panel for these 2 panels, or consider other layout managers like BoxLayout, etc
I have a JPanel to which when a button is pressed I want to add a new JLabel and JTextField too. However, I can't seem to get it working.
Is there an issue with my ActionListener, and if not, how could this be achieved?
JPanel south = new JPanel();
JButton add = new JButton("Add");
ActionListener addListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel mL = new JLabel("MOD: ");
mR.add(mL);
JTextField mM = new JTextField(10);
mR.add(mM);
mR.repaint();
}
};
add.addActionListener(addListener);
south.add(add);
add(south, BorderLayout.NORTH);
The layout of the mR panel is a grid layout set to allow multiple rows and two columns.
Call mR.revalidate() before repaint();
See my answer on a previous SO question for some sample code which dynamically adds a component to a container