I have 2 JPanels and 1 JFrame, and I'm trying to switch between panels when I click a button..
I don't want to use CardLayout, because I want different panels and with CardLayouts I just can have the same button for both.
My code is:
package javaapplication2;
import javax.swing.JPanel;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
public NewJFrame() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(121, 183, 60));
setSize(200, 300);
setResizable(false);
/**panel1**/
jButton1 = new javax.swing.JButton();
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.setText("jButton1");
panel1.setBackground(new java.awt.Color(121, 183, 60));
panel1.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton1)
.addContainerGap(172, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton1)
.addContainerGap(158, Short.MAX_VALUE))
);
/**panel2**/
jButton2 = new javax.swing.JButton();
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton2.setText("jButton2");
panel2.setBackground(new java.awt.Color(101, 13, 61));
panel2.setMaximumSize(new java.awt.Dimension(100, 200));
javax.swing.GroupLayout layout2 = new javax.swing.GroupLayout(panel2);
panel2.setLayout(layout2);
layout2.setHorizontalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jButton2)
.addContainerGap(172, Short.MAX_VALUE))
);
layout2.setVerticalGroup(
layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout2.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jButton2)
.addContainerGap(158, Short.MAX_VALUE))
);
add(panel2);
pack();
}
public void changePanel(){
getContentPane().removeAll();
add(panel1);
invalidate();
repaint();
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
changePanel();
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
}
Here is one small example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2(contentPane);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel)
{
contentPane = panel;
setOpaque(true);
setBackground(Color.RED.darker().darker());
//construct components
jcomp4 = new JButton ("openNewWindow");
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add(jcomp4);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
class MyPanel2 extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
public MyPanel2(JPanel panel)
{
contentPane = panel;
setOpaque(true);
setBackground(Color.GREEN.darker().darker());
//construct components
jcomp1 = new JButton ("Back");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
LATEST EDIT
Show JPanel of your choice, inside CardLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private MyPanel2 panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane, this);
panel2 = new MyPanel2(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel2(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp4;
private JPanel contentPane;
private JComboBox choiceBox;
public MyPanel(JPanel panel, CardLayoutExample cle)
{
choiceBox = cle.getChoiceBox();
contentPane = panel;
setOpaque(true);
setBackground(Color.RED.darker().darker());
//construct components
jcomp4 = new JButton ("Show New Panel");
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp4);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
class MyPanel2 extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel2(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Related
I'm trying to create a JFrame with one main panel contains two panels: left sub-panel has add and remove buttons which will dynamically add and remove components; right panel contains regular component. My code works find when there is only one panel, fails when used inside sub-panel.
public class MultiPanel extends JFrame{
static MultiPanel myFrame;
static int countMe = 0;
JPanel mainPanel;
JPanel userPanel;
JPanel contentPanel;
private static void iniComponents() {
myFrame = new MultiPanel();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.prepareUI();
myFrame.pack();
myFrame.setVisible(true);
}
private void prepareUI() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("My Title");
setPreferredSize(new java.awt.Dimension(1280, 720));
setSize(new java.awt.Dimension(1280, 720));
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
userPanel = new JPanel();
// userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.Y_AXIS));
mainPanel.add(userPanel);
JButton buttonAdd = new JButton("Add subPanel");
buttonAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userPanel.add(new subPanel());
myFrame.pack();
}
});
JButton buttonRemoveAll = new JButton("Remove All");
buttonRemoveAll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
userPanel.removeAll();
myFrame.pack();
}
});
contentPanel = new JPanel();
JLabel jLabel1 = new JLabel("Content here");
contentPanel.add(jLabel1);
mainPanel.add(contentPanel);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(mainPanel)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(mainPanel)
);
// getContentPane().add(userPanel, BorderLayout.WEST);
// getContentPane().add(contentPanel, BorderLayout.EAST);
// getContentPane().add(buttonAdd, BorderLayout.PAGE_START);
// getContentPane().add(buttonRemoveAll, BorderLayout.PAGE_END);
}
private class subPanel extends JPanel {
subPanel me;
public subPanel() {
super();
me = this;
JLabel myLabel = new JLabel("This is subPanel(): " + countMe++);
add(myLabel);
JButton myButtonRemoveMe = new JButton("remove me");
myButtonRemoveMe.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
me.getParent().remove(me);
myFrame.pack();
}
});
add(myButtonRemoveMe);
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
iniComponents();
});
}
}
I also wonder what is the proper way to write about the layout, aligning and organizing components seems to be painful for me.
I've been trying for days to access some variables from a class above in an ActionListener, but I fail all the time :( What am I doing wrong? I hope you can help me folks.
public class FileFrameBetterStructured extends JFrame {
protected FileModel fileModel = new FileModel();
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
TableRowSorter<TableModel> TableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
In the ActionListener I want to access the variables: button, filterText and TableRowSorter. THANK YOU!
Add this to the top of your class:
protected static JButton button;
protected static JTextField filterText;
protected static TableRowSorter<TableModel> TableRowSorter;
Change your code as following
public class FileFrameBetterStructured extends JFrame {
static JButton button;
static JTextField filterText;
staitc TableRowSorter<TableModel> tableRowSorter;
protected FileModel fileModel = new FileModel();
FileFrameBetterStructured()
{
// Set Preferences
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create table
FileModel fileModel = new FileModel();
JTable FileTable = new JTable(fileModel);
tableRowSorter = new TableRowSorter<TableModel>(fileModel);
FileTable.setRowSorter(TableRowSorter);
FileTable.setColumnSelectionAllowed(true);
FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
JScrollPane JScrollPane = new JScrollPane(FileTable);
getContentPane().add(JScrollPane, BorderLayout.CENTER);
// Create textfilter
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
filterText = new JTextField("");
panel.add(filterText, BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
button = new JButton("Filter");
add(button, BorderLayout.SOUTH);
setSize(300, 250);
setVisible(true);
}
public static void main(String args[]) {
final FileFrameBetterStructured FileFrame = new FileFrameBetterStructured();
// Integrate ActionListener for textfilter
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
TableRowSorter.setRowFilter(null);
} else {
TableRowSorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
}
}
Hope it helps.
As you can see from the image above some of the text is being cut off :(
Code:
package malgm.school.clockui.ui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import malgm.school.clockui.ClockUI;
import malgm.school.clockui.ResourceLoader;
public class ClockFrame extends JFrame {
private static final long serialVersionUID = 1L;
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 200;
public ClockFrame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
}
public void relocalize() {
//Wipe controls
this.getContentPane().removeAll();
this.setLayout(null);
initComponents();
}
#SuppressWarnings("unused")
private void initComponents() {
setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
speakButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec(ClockUI.dir + "/SpeakingClock.exe");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
FONT: http://www.dafont.com/digital-7.font
Any help will be greatly appreciated
A key to success with Swing layouts is to avoid setLayout(null) and to pack() the enclosing Window. This lets the contained components adopt their preferred sizes, as shown below. To avoid this pitfall, don't invoke setResizable(false).
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/23551260/230513 */
public class ClockFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ClockFrame cf = new ClockFrame();
}
});
}
public ClockFrame() {
setTitle("Clock");
setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
#SuppressWarnings("unused")
private void initComponents() {
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
JLabel time = new JLabel("00:00");
time.setFont(time.getFont().deriveFont(72f));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
After
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
Add time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
After it will look like:
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
change your constructor definition to (EDITED)
public Frame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
setSize(850, 650);
setLocationRelativeTo(null);
setVisible(true);
}
I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel. I need to add JTextfield and JLabel to panel1 and I add panel1 to panel. I need to add JTextFields and JLabels in a Top-Bottom manner and set layout. panel1 and panel are instances of JPanel.
My code :
public class MakeScrollablePanel extends JFrame implements ActionListener
{
static JButton jButton11,jButton12;
static JPanel panel,panel1;
static JTextField jTextFields;
static JLabel label;
static JComboBox<String> jComboBox;
static Dimension dime,dime1,dime2,dime3,dime4,dime5;
static JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
BoxLayout bx=null;// #jve:decl-index=0:
int count=1,i=0;
public MakeScrollablePanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11);
add(scroll);
dime=new Dimension(600,550);
setSize(dime);
setTitle("Priyank Panel");
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
private void Show()
{
jButton11=new JButton("Add Designation");
panel=new JPanel();
bx=new BoxLayout(panel,BoxLayout.Y_AXIS);
scroll=new JScrollPane(panel);
dime1=new Dimension(500,3000);
dime5=new Dimension(500,450);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230 , 255));
jButton11.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==jButton11)
{
label=new JLabel("Add Designation "+count +" :-");
jTextFields=new JTextField(30);
panel1=new JPanel();
panel1.setBackground(new Color(204, 230 , 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel1.revalidate();
panel.revalidate();
panel.updateUI();
count++;
i++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
still not working
still I can't see thre any problem with (depsite fact that there is used BoxLayout instead of GridLayout, but result could be very similair in the case that is used many JTextFields)
.
.
from (little bit) modifyied OPs code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MakeScrollablePanel extends JFrame implements ActionListener {
private JButton jButton11, jButton12;
private JPanel panel, panel1;
private JTextField jTextFields;
private JLabel label;
private JComboBox<String> jComboBox;
private Dimension dime, dime1, dime2, dime3, dime4, dime5;
private JScrollPane scroll;
private GridBagConstraints panelConstraints = new GridBagConstraints();
private BoxLayout bx = null;// #jve:decl-index=0:
private int count = 1, i = 0;
public MakeScrollablePanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show();
add(jButton11, BorderLayout.NORTH);
add(scroll);
setTitle("Priyank Panel");
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
private void Show() {
jButton11 = new JButton("Add Designation");
panel = new JPanel();
bx = new BoxLayout(panel, BoxLayout.Y_AXIS);
scroll = new JScrollPane(panel);
dime5 = new Dimension(500, 150);
panelConstraints = new GridBagConstraints();
scroll.setPreferredSize(dime5);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setLayout(bx);
panel.add(Box.createHorizontalBox());
panel.setBorder(LineBorder.createBlackLineBorder());
panel.setBackground(new Color(204, 230, 255));
jButton11.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == jButton11) {
label = new JLabel("Add Designation " + count + " :-");
jTextFields = new JTextField(30);
panel1 = new JPanel();
panel1.setBackground(new Color(204, 230, 255));
panel1.add(label);
panel1.add(jTextFields);
panel.add(panel1);
panel.revalidate();
panel.repaint();
count++;
i++;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MakeScrollablePanel();
}
});
}
}
I want to know how to add components dynamically to a JDialog. I know there is a similar question on SO here, but as you can see, I have his solution as a part of my code.
So the idea is that on click of the button, I need to add a component on the dialog. The sample code is below:
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
Test test = new Test();
test.createDialog();
}
public void createDialog() {
DynamicDialog dialog = new DynamicDialog(this);
dialog.setSize(300, 300);
dialog.setVisible(true);
}
}
class DynamicDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
public DynamicDialog(final JFrame owner) {
super(owner, "Dialog Title", Dialog.DEFAULT_MODALITY_TYPE);
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createRigidArea(new Dimension(3, 10)));
panel.add(createLabel("Click on add"));
panel.add(Box.createRigidArea(new Dimension(23, 10)));
panel.add(createLabel("To add another line of text"));
panel.add(Box.createHorizontalGlue());
mainPanel.add(panel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
JButton button = new JButton();
button.setText("Add another line");
buttonPanel.add(button);
mainPanel.add(buttonPanel);
mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Container contentPane = owner.getContentPane();
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
contentPane.add(_panel);
contentPane.validate();
contentPane.repaint();
owner.pack();
}
});
pack();
setLocationRelativeTo(owner);
this.add(mainPanel);
}
JLabel createLabel(String name) {
JLabel label = new JLabel(name);
return label;
}
}
If you add it to the main panel it will work, you were adding it to the content pane of the frame which it seems it does not show up anywhere.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JPanel _panel = new JPanel();
_panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
_panel.add(Box.createHorizontalGlue());
_panel.add(createLabel("Added!"));
mainPanel.add(_panel);
mainPanel.validate();
mainPanel.repaint();
owner.pack();
}
})