Clicking on JTable Cell should display Form into a Container - java

I am new to Java Swing and I am trying to create an application.
I have a MainApplication.java file which extends SingleFrameApplication and where I am creating a JPanel named MainPanel. This MainPanel has an AnimatingSplitPane with VERTICAL_SPLIT named SplitPane.
On the Top of the SplitPane, I am adding another JPanel named MainContainer. On the bottom of the SplitPane, I am adding a JPanel named FormContainer. The MainContainer loads the another class named DataSheetTable (a JPanel having JTable).
Now, when user clicks on the cells of the DataSheetTable, I want to load the form into the FormContainer. I don't know, how can I achieve this.
For instance, DatasheetTable has Column1, Column2 and Column3. When user clicks on any cell of Column1, I need to show Form1 into the FormContanier. If it clicks on Column2 cell then I need to show Form2 into FormContanier.
Please let me know with some sample code, how can I achieve loading the forms on the fly to FormContainer.
![Thank you in advance.]
Image description for the issue
Here is sample code for App.java
public class App extends SingleFrameApplication {
#Override protected void startup() {
configureDefaults();
View view = getMainView();
view.setComponent(createMainPanel());
show(view);
}
protected JComponent createMainPanel() {
// Create main panel with demo selection on left and demo/source on right
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Create splitpane on right to hold demo and source code
splitPane = new AnimatingSplitPane(JSplitPane.VERTICAL_SPLIT);
mainPanel.add(splitPane, BorderLayout.CENTER);
// Create panel to contain main panel
mainContainer = new JPanel();
splitPane.setTopComponent(mainContainer);
DataSheetTable dataSheetTable = new DataSheetTable();
mainContainer.add(dataSheetTable, BorderLayout.CENTER);
dataSheetTable.start();
formContainer = new JPanel(new BorderLayout());
splitPane.setBottomComponent(formContainer);
formContainer.add(new OrganizationForm());
return mainPanel;
}
}
Here is sample code for DataSheetTable.java file
public class DataSheetTable extends JPanel {
........
controlPanel = createControlPanel();
add(controlPanel, BorderLayout.NORTH);
routingTable = new JTable(routingModel);
.........
}

So here is your code for intercepting events of table cell clicks:
public class App extends JFrame {
private DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Value1", "Value2", "Value3" }, { "Object1", "Object2", "Object3" } }, new String[] {
"Column1", "Column2", "Column3" });
private JTable table = new JTable(model);
private JPanel bottomPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App a = new App();
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
}
public App() {
JSplitPane pane = new JSplitPane();
pane.setOrientation(SwingConstants.HORIZONTAL);
pane.setLeftComponent(new JScrollPane(table));
bottomPanel = new JPanel();
bottomPanel.add(new JLabel("properties for column will be here"));
pane.setRightComponent(bottomPanel);
add(pane);
ListSelectionListener listener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int column = table.getSelectedColumn();
int row = table.getSelectedRow();
if(row != -1 && column != -1) {
bottomPanel.removeAll();
//Here you add your components/create appropriate panel
//e.g. bottomPanel.add(new PropertiesPanelForValue1(...));
bottomPanel.add(new JLabel("User selected column " + column + " and row " + row
+ " with value: '" + table.getValueAt(row, column) + "'"));
bottomPanel.revalidate();
}
}
};
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
pack();
pane.setDividerLocation(0.3);
setSize();
}
private void setSize() {
double widthPart = 0.3;
double heightPart = 0.5;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) (screenSize.getWidth() * widthPart);
int height = (int) (screenSize.getHeight() * heightPart);
setSize(width, height);
Dimension windowSize = getSize();
int x = (int) ((screenSize.getWidth() - windowSize.getWidth()) / 2);
int y = (int) ((screenSize.getHeight() - windowSize.getHeight()) / 2);
setLocation(x, y);
}
}
EDIT
Looking at your update: Just add to DataSheetTable constructor reference to your FormContainer:
formContainer = new JPanel(new BorderLayout());
splitPane.setBottomComponent(formContainer);
formContainer.add(new OrganizationForm());
DataSheetTable dataSheetTable = new DataSheetTable(formContainer);
mainContainer.add(dataSheetTable, BorderLayout.CENTER);
dataSheetTable.start();
and in DataSheetTable add listener:
public class DataSheetTable extends JPanel {
public DataSheetTable(final FormContainer formContainer) {
........
controlPanel = createControlPanel();
add(controlPanel, BorderLayout.NORTH);
routingTable = new JTable(routingModel);
ListSelectionListener listener = new ListSelectionListener() {...};
routingTable.getSelectionModel().addListSelectionListener(listener);
routingTable.getColumnModel().getSelectionModel().addListSelectionListener(listener);
.........
}
}

Related

More than 1 object in a single JFrame

I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.
Here is Calculator:
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
/***********************************************************************
***********************************************************************
**********************************************************************/
JPanel southPanel = new JPanel(); //New panel for the artimatic buttons
southPanel.setBorder(BorderFactory.createEtchedBorder());
timesButton = new JButton("Multiplication");
southPanel.add(timesButton);
timesButton.addActionListener(this);
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
addButton = new JButton("Addition");
southPanel.add(addButton);
addButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
/**
* clear()
* Resets the x and y field to 0 after invalid integers were input
*/
public void clear() {
xfield.setText("0");
yfield.setText("0");
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
clear();
return ;
}
if(event.getSource().equals(timesButton)) { //Button pressed was multiply
result.setText(Integer.toString(xVal*yVal));
}
else if(event.getSource().equals(divideButton)) { //Button pressed was division
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(event.getSource().equals(subtractButton)) { //Button pressed was subtraction
result.setText(Integer.toString(xVal-yVal));
}
else if(event.getSource().equals(addButton)) { //Button pressed was addition
result.setText(Integer.toString(xVal+yVal));
}
}
}
And here is my current main:
public class DemoCalculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculators");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator calc = new Calculator();
Calculator2 calc2 = new Calculator2();
JPanel calcPanel = new JPanel(new BorderLayout());
JPanel calcPanel2 = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//calcPanel.add(calc, BorderLayout.CENTER);
//calcPanel2.add(calc2, BorderLayout.CENTER);
mainPanel.add(calcPanel);
mainPanel.add(calcPanel2);
calcPanel.add(mainPanel);
mainFrame.getContentPane().add(calcPanel);
mainFrame.getContentPane().add(calcPanel2);
mainFrame.pack();
mainFrame.setVisible(true);
}
}
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.
public class Calculator{
JPanel panel;
public Calculator(){
panel = new JPanel();
/*
* Add labels and buttons etc.
*/
panel.add(buttons);
panel.add(labels);
}
//Method to return the JPanel
public JPanel getPanel(){
return panel;
}
}
Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.
public class DemoCalculator {
public static void main(String[] args) {
JPanel cal1,cal2;
JFrame frame = new JFrame("Calculators");
frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}

JLayeredPane with JPanel

The problem: I have no control on implementing more into the histogram package, so I create an array of buttons and overlay them on top of the histogram using JLayeredPane. However, I cannot get both the histogram plot and the buttons panels to scale when the JFrame is enlarged or contracted.
The JLayedPane is composed of 2 JPanels, see MWE.
To repeat the issue, just run program and extend JFrame.
I have read the following on SO posts; jlayeredpane-with-gridlayout, jlayeredpane-with-a-layoutmanager, jlayeredpane-not-resizing-with-jframe, resize-jframe-to-jpanels-inside-jlayeredpane, automatic-content-resizing-of-jlayeredpane,
as well as the Oracle page on JLayeredPane which has some examples
As useful as these links were, I still cannot get both JPanels to extend/contract with the JFrame.
Question: Is there a way to get both JPanels in the JLayeredPane to rescale without implementing a new layout? If new layout is needed, would someone please provide a MWE on how to do such?
public class FrameDemo extends JPanel {
private JLayeredPane layeredPane;
private final int width = 800;
private final int height = 800;
private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)", "Red (3)", "Green (4)", "Blue (5)" };
private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red, Color.green, Color.blue };
public FrameDemo() {
setLayout(new BorderLayout());
init();
addPanels();
add(layeredPane, BorderLayout.CENTER);
}
private void init() {
this.layeredPane = new JLayeredPane();
this.layeredPane.setPreferredSize(new Dimension(width, height));
this.layeredPane.setBorder(BorderFactory.createTitledBorder("Histogram should go here"));
this.layeredPane.setLayout(new BorderLayout());
}
private void addPanels() {
this.layeredPane.add(createHistogramPanel(), BorderLayout.CENTER, new Integer(1));
this.layeredPane.add(createButtonPanel(), BorderLayout.CENTER, new Integer(0));
this.layeredPane.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Dimension size = layeredPane.getSize(); // get size
createHistogramPanel().setSize(size); // push size through
createButtonPanel().setSize(size); // push size trhough
// otherChildOfLayers.setSize(size); // push size trhough
layeredPane.revalidate(); // revalidate to see updates
layeredPane.repaint(); // "Always invoke repaint after
// revalidate"
}
});
}
private JPanel createHistogramPanel() {
JPanel histpanel = new JPanel();
histpanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i], layerColors[i]);
histpanel.add(label);
}
histpanel.setOpaque(false);
histpanel.setBounds(10, 10, width, height);
return histpanel;
}
private JLabel createColoredLabel(String text, Color color) {
JLabel label = new JLabel("");
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setPreferredSize(new Dimension(120, 120));
return label;
}
private JPanel createButtonPanel() {
ButtonGroup buttons = new ButtonGroup();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < 6; i++) {
final int placer = i + 1;
JButton freshButton = new JButton();
freshButton.addActionListener(e -> {
System.out.println("Button " + placer + " clicked");
});
freshButton.setText("Button " + (i + 1));
freshButton.setOpaque(true);
freshButton.setContentAreaFilled(false);
freshButton.setBorderPainted(false);
freshButton.setBounds(new Rectangle(132, 75 + (i * 20), 40, 20));
buttonPanel.add(freshButton, null);
buttons.add(freshButton);
}
buttonPanel.setOpaque(false);
buttonPanel.setBounds(10, 10, width, height);
return buttonPanel;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new FrameDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Your code won't work because in componentResized you're creating new panels and applying the size to them. You need to resize the existing panels added to the layered pane. This could be done by assigning histogramPanel and buttonPanel as instance variables.

Refresh a JTable after insert data in mysql database

i´ve been trying to refresh de JTable after inserting data in MySql, but i cant manage to make it work.
The data is filled in the agregar JPanel and saved after clicking a button, checking in the mysql console, the data is added to the database, but when i open the table it doesn´t update unless i restart the program.
This is My code:
public class verTodos extends JPanel {
contactoDAO dao = new contactoDAO();
List<contacto> contactos = dao.getAll();
private JTable table;
public verTodos() {
String[] colName = { "Id", "Nombre", "Apellido", "Telefono",
"Direccion", "Email", "Rubro1", "Rubro2", "Rubro3" };
Object[][] obj = new Object[contactos.size()][10];
for (int i = 0; i < contactos.size(); i++) {
contacto c = contactos.get(i);
obj[i][0] = c.getId();
bj[i][1] = c.getNombre();
obj[i][2] = c.getApellido();
obj[i][3] = c.getTelefono();
obj[i][4] = c.getDireccion();
obj[i][5] = c.getEmail();
obj[i][6] = c.getRubro1();
obj[i][7] = c.getRubro2();
obj[i][8] = c.getRubro3();
setBounds(100, 100, 800, 300);
}
DefaultTableModel contactTableModel = new DefaultTableModel(obj,colName);
table = new JTable(contactTableModel);
setLayout(new BorderLayout(0, 0));
contactTableModel.fireTableDataChanged();
contactTableModel.setColumnIdentifiers(colName);
add(table.getTableHeader(), BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
repaint();
}
}
this is the main screen that contains the JPanels:
public class principal extends JFrame {
JFrame frame = new JFrame();
JPanel container = new JPanel();
CardLayout cl = new CardLayout();
private final JMenuBar menuBar = new JMenuBar();
/.....
.....
private final JMenuItem mntmVerTodos = new JMenuItem("Ver todos");
private final JMenuItem mntmAgregar = new JMenuItem("Agregar");
agregar ag = new agregar();
verTodos ver = new verTodos();
...
...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new principal();
}
});
}
public principal() {
textField.setMaximumSize(new Dimension(300, 500));
textField.setBounds(new Rectangle(0, 0, 30, 0));
textField.setColumns(10);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int X = (screen.width / 2) - (1366 / 2);
int Y = (screen.height / 2) - (720 / 2);
frame.setBounds(X, Y, 1363, 720);
container.setLayout(cl);
ver.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(ver, "ver");
container.add(ag, "ag");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
frame.getContentPane().add(container);
frame.setJMenuBar(menuBar);
menuBar.add(mnNewMenu);
cl.show(container, "ver");
mntmVerTodos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "ver");
}
});
mnContactos.add(mntmVerTodos);
mnContactos.add(mntmAgregar);
mntmModificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "mod");
}
});
menuBar.add(btn);
frame.setVisible(true);
}
}
You need to repopulate your model once the database has been updated. Add a refresh button that when clicked, updates contactTableModel

How can I add JButtons in a DefaultListModel?

I am making a battleship game and I'm trying to figure out a way to control buttons in a pane so that I can drag drop them and keep track of their indexes with a default list model.If I add string or ImageIcons it works fine but with buttons I get something different.
Here's my code:
public class ListModelExample extends JPanel {
JList list;
DefaultListModel model;
int counter = 15;
public ListModelExample() {
setLayout(new BorderLayout());
model = new DefaultListModel();
list = new JList(model);
JScrollPane pane = new JScrollPane(list);
JButton addButton = new JButton("Add Element");
JButton removeButton = new JButton("Remove Element");
final JButton button = new JButton("button");
for (int i = 0; i < 5; i++)
model.addElement(button);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addElement(button);
counter++;
}
});
removeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (model.getSize() > 0)
model.removeElementAt(0);
}
});
add(pane, BorderLayout.NORTH);
add(addButton, BorderLayout.WEST);
add(removeButton, BorderLayout.EAST);
}
public static void main(String s[]) {
JFrame frame = new JFrame("List Model Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample());
frame.setSize(260, 200);
frame.setVisible(true);
}
}
If I add Buttons I get this result:
So my question is: How is it possible to make buttons appear normally and not as text in a default list model?
this could be done only by Renderer, put only String value to the DefaultListModel
don't put any JComponents to the XxxModel
I'd be use JPanel with JButtons instead of JList as containers (required to change getScrollableBlockIncrement / getScrollableUnitIncrement for natural scrolling in compare with JList or JTable)
example about both a.m. ways
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
public class ListButtons extends JFrame {
private static final long serialVersionUID = 1L;
public ListButtons() {
setLayout(new GridLayout(0, 2, 10, 10));
DefaultListModel model = new DefaultListModel();
model.addElement(createButtons("one"));
model.addElement(createButtons("two"));
model.addElement(createButtons("three"));
model.addElement(createButtons("four"));
model.addElement(createButtons("five"));
model.addElement(createButtons("six"));
model.addElement(createButtons("seven"));
model.addElement(createButtons("eight"));
model.addElement(createButtons("nine"));
model.addElement(createButtons("ten"));
model.addElement(createButtons("eleven"));
model.addElement(createButtons("twelwe"));
JList list = new JList(model);
list.setCellRenderer(new PanelRenderer());
JScrollPane scroll1 = new JScrollPane(list);
final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
scrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar.getValue());
}
});
add(scroll1);
JScrollPane scroll2 = new JScrollPane(createPanel());
add(scroll2);
final JScrollBar scrollBar1 = scroll2.getVerticalScrollBar();
scrollBar1.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("JScrollBar's current value = " + scrollBar1.getValue());
}
});
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
panel.add(createButtons("one"));
panel.add(createButtons("two"));
panel.add(createButtons("three"));
panel.add(createButtons("four"));
panel.add(createButtons("five"));
panel.add(createButtons("six"));
panel.add(createButtons("seven"));
panel.add(createButtons("eight"));
panel.add(createButtons("nine"));
panel.add(createButtons("ten"));
panel.add(createButtons("eleven"));
panel.add(createButtons("twelwe"));
return panel;
}
public static JButton createButtons(String text) {
JButton button = new JButton(text);
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ListButtons frame = new ListButtons();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(270, 200);
frame.setVisible(true);
}
});
}
class PanelRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JButton renderer = (JButton) value;
renderer.setBackground(isSelected ? Color.red : list.getBackground());
return renderer;
}
}
}

all individual panels are not shown inside root panel

I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED.
But the problem is all individual panels are not shown inside root panel.
Code:
JScrollPane scPanel=new JScrollPane();
JPanel rootPanel=new JPanel();
rootPanel.setLayout(new FlowLayout());
JPanel indPanel = new JPanel();
rootPanel.add(indPanel);
JPanel indPanel2 = new JPanel();
rootPanel.add(indPanel2);
//.....like this added indPanals to rootPanel.
scPanel.setViewPortView(rootPanel);
//scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area.
I am not able to see all individual panels,
Please suggest me.
Edit: code snippet from double post:
MosaicFilesStatusBean mosaicFilesStatusBean = new MosaicFilesStatusBean();
DefaultTableModel tableModel = null;
tableModel = mosaicFilesStatusBean.getFilesStatusBetweenDates(startDate, endDate);
if (tableModel != null) {
rootPanel.removeAll();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
for (int tempRow = 0; tempRow < tableModel.getRowCount(); tempRow++) {
int fileIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 0).toString());
String dateFromTemp = tableModel.getValueAt(tempRow, 3).toString();
String dateToTemp = tableModel.getValueAt(tempRow, 4).toString();
int processIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 5).toString());
int statusIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 6).toString());
String operatingDateTemp = tableModel.getValueAt(tempRow, 7).toString();
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, dateFromTemp, dateToTemp, processIdTemp, statusIdTemp, operatingDateTemp);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
}
The main reason, why you couldn't see your JPanel is that you are using FlowLayout as the LayoutManager for the rootPanel. And since your JPanel added to this rootPanel has nothing inside it, hence it will take it's size as 0, 0, for width and height respectively. Though using GridLayout such situation shouldn't come. Have a look at this code example attached :
import java.awt.*;
import javax.swing.*;
public class PanelAddition
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Panel Addition Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
JScrollPane scroller = new JScrollPane();
CustomPanel panel = new CustomPanel(1);
contentPane.add(panel);
scroller.setViewportView(contentPane);
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
for (int i = 2; i < 20; i++)
{
CustomPanel pane = new CustomPanel(i);
contentPane.add(pane);
contentPane.revalidate();
contentPane.repaint();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelAddition().createAndDisplayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
public CustomPanel(int num)
{
JLabel label = new JLabel("" + num);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200, 50));
}
}
Don't use FlowLayout for the rootPanel. Instead consider using BoxLayout:
JPanel rootPanel=new JPanel();
// if you want to stack JPanels vertically:
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
Edit 1
Here's an SSCCE that's loosely based on your latest code posted:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class PanelsEg extends JPanel {
private static final int MAX_ROW_COUNT = 100;
private Random random = new Random();
private JPanel rootPanel = new JPanel();
public PanelsEg() {
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(rootPanel);
scrollPane.setPreferredSize(new Dimension(400, 400)); // sorry kleopatra
add(scrollPane);
add(new JButton(new AbstractAction("Foo") {
#Override
public void actionPerformed(ActionEvent arg0) {
foo();
}
}));
}
public void foo() {
rootPanel.removeAll();
// rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS)); // only need to set layout once
int rowCount = random.nextInt(MAX_ROW_COUNT);
for (int tempRow = 0; tempRow < rowCount ; tempRow++) {
int fileIdTemp = tempRow;
String data = "Data " + (tempRow + 1);
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, data);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
rootPanel.repaint(); // don't forget to repaint if removing
}
private class MosaicPanel extends JPanel {
public MosaicPanel(int fileIdTemp, String data) {
add(new JLabel(data));
}
}
private static void createAndShowGui() {
PanelsEg mainPanel = new PanelsEg();
JFrame frame = new JFrame("PanelsEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This SSCCE works, in that it easily shows removing and adding JPanels to another JPanel that is held by a JScrollPane. If you're still having a problem, you should modify this SSCCE so that it shows your problem.

Categories

Resources