I have to design a swing game where one side is a grid and the other side is somewhat of a display panel where I have several JLabels and a JButton. But no matter if I use setSize(); or setPrefferedSize (); or setBounds(); or even setPrefferedSize(new Dimension()); it will not become smaller but instead stretches the entirety of that section. Any JLabel/JButton aligned in the center takes up the entire center. How do I fix this?
This is the code to my class referencing to another class in the project containing the grid:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Scoreboard extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
public Scoreboard (int score){
setLayout(new BorderLayout());
setSize(490,400);
setPreferredSize(getSize());
setBackground(Color.BLUE);
title = new JLabel();
title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
title.setSize(200,200);
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
coord.setSize(200,400);
coord.setBackground(Color.RED);
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
}
The following code does not solve the problem. Instead it shows some tips related to your question, as well as some others.
In general try to avoid "manually control" components layout, but use the right layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class Scoreboard extends JPanel{
JLabel scoreLabel;
JLabel coord;
JLabel title;
JButton quit;
private final int W = 490;
private final int H = 400;
public Scoreboard (int score){
setLayout(new BorderLayout());
setPreferredSize(new Dimension(W, H));
setBackground(Color.BLUE);
title = new JLabel("My Title");
//if you use images in your SO posted code use web links
//title.setIcon(new ImageIcon("C:\\Users\\Rachel\\Workspace\\Assignment2\\Planet1.png"));
//title.setSize(200,200); run the code without it and see it has no effect
title.setHorizontalAlignment(SwingConstants.CENTER);
add (title,BorderLayout.NORTH);
scoreLabel = new JLabel("Score: "+Integer.toString(score));
scoreLabel.setSize(200,200);
scoreLabel.setBackground(Color.BLUE);
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setFont(new Font("Source Sans Pro", Font.BOLD, 40));
scoreLabel.setForeground(Color.WHITE);
//this is directly related to your question. You can't add 2 components
//to the center.
//instead add a JPanel to the center, apply a layout manager to it,
//and add scorelabel and quit button to that JPanel
add(scoreLabel, BorderLayout.CENTER);
coord = new JLabel ("Click the aliens!");
//coord.setSize(200,400); run the code without it and see it has no effect
coord.setBackground(Color.RED);
coord.setOpaque(true); //if you want the color show
coord.setHorizontalAlignment(SwingConstants.CENTER);
coord.setFont(new Font("Source Sans Pro", Font.BOLD, 20));
coord.setForeground(Color.WHITE);
add(coord,BorderLayout.SOUTH);
JButton quit = new JButton ("Quit Game");
//no need to set bounds. That is what the layout manager does
//quit.setBounds(20,30,50,30);
quit.setHorizontalAlignment(SwingConstants.CENTER);
add(quit, BorderLayout.CENTER);
}
//add main to your questions to make it runnable
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new Scoreboard(50);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Related
I am trying to learn Java Swing from a very old tutorial. As I was following the course I got stuck in a project where I was learning about GridBagLayout. When I called the function setLayout(new GridBagLayout());, Eclipse shows me 'GridBagLayout cannot be resolved to a type'. Even though I have imported java. awt. GridBagLayout.
Here's my code.
package com.swing11;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class FormPanel extends JPanel {
private JLabel nameLabel;
private JLabel occupationLabel;
private JTextField nameField;
private JTextField occupationField;
private JButton okButton;
public FormPanel() {
nameLabel = new JLabel("Name: ");
occupationLabel = new JLabel("Occupation: ");
nameField = new JTextField(10);
occupationField = new JTextField(25);
okButton = new JButton("Ok");
Dimension dim = getPreferredSize();
dim.width = 250;
setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("Add Person");
Border outterBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outterBorder, innerBorder));
setLayout(new GridBagLayout());
}
}
More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.
I've uploaded an image of the current program running :
As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.
Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.
Thanks for taking the time to read this!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
//Bottom Panel
JPanel GradePanel = new JPanel();
GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
GradePanel.setOpaque(false);
GradePanel.setPreferredSize(new Dimension(0 , 100));
GradePanel.add(resultField);
resultField.setAlignmentX(LEFT_ALIGNMENT);
GradePanel.add(nameResult);
GradePanel.add(gradeResult);
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(GradePanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and then the driver class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
Take time to read this the most flexible Layout Manager that commonly used by programmer :)
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read.
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
myBottomPanel mybottompanel = new myBottomPanel();//Object
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(mybottompanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class myBottomPanel extends JPanel{
public myBottomPanel()
{
this.setLayout(new GridBagLayout());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Constraints
GridBagConstraints nameResultConstraints = new GridBagConstraints();
GridBagConstraints gradeResultConstraints = new GridBagConstraints();
//Bottom Panel
setBorder(BorderFactory.createTitledBorder("Students/Results"));
setOpaque(false);
setPreferredSize(new Dimension(0 , 100));
nameResultConstraints.anchor = GridBagConstraints.LINE_START;
nameResultConstraints.weightx = 0.5;
nameResultConstraints.weighty = 0.5;
add(nameResult,nameResultConstraints);
add(gradeResult);
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and here is your Frame.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
OUTPUT
Hope this helps. :)
If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.
Maybe you can use a GridBagLayout. You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables.
Can anyone see the code ? I want to make a page that has a banner and a pannel in which cards will change on the requirement. I added the Banner in JFrame (That is working fine) but The problem is that " CardLayout Panel is not adding in the JFrame".
Actually, I need this.
When button is pressed only card1 change to card2 but banner will remain same.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class gui extends JFrame{
private static final long serialVersionUID = 1L;
JPanel
basic_panel,
card_Layout_panel,
banner_panel,
welcome_authenticaion_panel_card1;
CardLayout basic2;
JLabel
logo_label,
name_label;
public gui(){
server_login_gui();
add(basic_panel);
standard_gui();
}
public void server_login_gui(){
basic_panel = new JPanel();
basic_panel.setLayout(null);
basic_panel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
banner_panel = new JPanel();
banner_panel.setLayout(null);
banner_panel.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
banner_panel.setSize(680, 200);//(400,100,400,100);
//////Banner inner things//////////////////////////////////////////////////
logo_label = new JLabel("Logo");
logo_label.setBounds(30,40,100,100);
logo_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(logo_label);
name_label = new JLabel(" Name..... ");
name_label.setFont(new Font("Times new Roman", Font.BOLD | Font.ITALIC,25));
name_label.setBounds(200,80,400,50);
name_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(name_label);
////////////////////////////////////////////////////////////////////////
// basic_panel.add(banner_panel,BorderLayout.NORTH);
///////// Card Layout//////////////
basic2 = new CardLayout();
card_Layout_panel = new JPanel(basic2);
card_Layout_panel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 5));
basic_panel.add(card_Layout_panel,BorderLayout.CENTER);
welcome_authenticaion_panel_card1 = new JPanel();
welcome_authenticaion_panel_card1.setLayout(null);
welcome_authenticaion_panel_card1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
welcome_authenticaion_panel_card1.setSize(680, 200);//(400,100,400,100);
welcome_authenticaion_panel_card1.setBounds(0,200,680,460);
card_Layout_panel.add(welcome_authenticaion_panel_card1, "1");
basic_panel.add(card_Layout_panel,BorderLayout.CENTER);
/////////////////////////////////////////////////////////////////////////
}
public void standard_gui(){
setSize(700,700);
setTitle("System");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
I want to make a page that has a banner and a pannel in which cards
will change on the requirement.
your component aren't focusable, there is required some event (JButton, Swing Timer) for switching the view by using CardLayout
for more info about CardLayout to read Oracle tutorial, for working code exampes, tons code examples are here
you code works without NullLayout (by set BorderLayout to parent JPanel), default LayoutManager for Jpanel is FlowLayout (accepts only getPreferredSize, childs aren't resizable with its parent/s)
my question is for why reason is there code line basic_panel.add(card_Layout_panel, BorderLayout.CENTER); twice, and another ...
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel basic_panel, card_Layout_panel,
banner_panel, welcome_authenticaion_panel_card1;
private CardLayout basic2;
private JLabel logo_label, name_label;
public Gui() {
server_login_gui();
add(basic_panel);
standard_gui();
}
public void server_login_gui() {
basic_panel = new JPanel();
basic_panel.setLayout(new BorderLayout(10, 10));
basic_panel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
banner_panel = new JPanel();
//banner_panel.setLayout(null);
banner_panel.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
banner_panel.setSize(680, 200);//(400,100,400,100);
//////Banner inner things//////////////////////////////////////////////////
logo_label = new JLabel("Logo");
//logo_label.setBounds(30, 40, 100, 100);
logo_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(logo_label);
name_label = new JLabel(" Name..... ");
name_label.setFont(new Font("Times new Roman", Font.BOLD | Font.ITALIC, 25));
//name_label.setBounds(200, 80, 400, 50);
name_label.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
banner_panel.add(name_label);
////////////////////////////////////////////////////////////////////////
basic_panel.add(banner_panel, BorderLayout.NORTH);
///////// Card Layout//////////////
basic2 = new CardLayout();
card_Layout_panel = new JPanel(basic2);
card_Layout_panel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 5));
basic_panel.add(card_Layout_panel, BorderLayout.CENTER);
welcome_authenticaion_panel_card1 = new JPanel();
welcome_authenticaion_panel_card1.setLayout(null);
welcome_authenticaion_panel_card1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
welcome_authenticaion_panel_card1.setSize(680, 200);//(400,100,400,100);
//welcome_authenticaion_panel_card1.setBounds(0, 200, 680, 460);
card_Layout_panel.add(welcome_authenticaion_panel_card1, "1");
basic_panel.add(card_Layout_panel, BorderLayout.CENTER);
/////////////////////////////////////////////////////////////////////////
}
public void standard_gui() {
setSize(700, 700);
setTitle("System");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
}
}
you're doing this basic_panel.add(card_Layout_panel,BorderLayout.CENTER); twice, hence the error. ( check before and after the welcome_authentication_panel_card )
I tried creating simple GUI using JFrame with below code.
package sorting_array_gui;
package sorting_array_gui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
public class userwindow extends JFrame {
private static final long serialVersionUID = 1L;
public userwindow() {
super("A Programm to Sort Your Array");
setSize(1000,600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
}
}
When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing.
Why is that happening.
"When I added JTextfield , JPlane misbehaved and even JButton and JLabel stoped showing."
I don't get this behavior with your code. But you should note the below.
setVisible(true); should be that last thing you do after adding all components.
public userwindow() {
super("A Programm to Sort Your Array");
JPanel p1= new JPanel();
JButton b1= new JButton("Click Here");
p1.add(b1);
JTextField t1= new JTextField();
p1.add(t1);
JLabel l1= new JLabel("This is a Lable");
p1.add(l1);
add(p1,BorderLayout.CENTER);
pack(); <--- PACK frame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true); <--- LAST
}
Also, you should set a size to your text field using the constructor that sets the column size
JTextField t1 = new JTextField(20);
Also, you should use pack() instead of setSize(). If you just pack(), everything should be visible, as the preferred sizes of all the components are respected.
Also note, if you want to add any other components to the JFrame you need to specify a BorderLayout position for each component, with no positions being used more than once.
See Laying out Components Within a Container
I have frame with a button and a JPanel as I named panel, I want after I clicked the button add an inner panel to my panel. But this but there is a problem with this! because after adding second panel it didn't add any other panel.
Code
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.JTextField;
public class DrawImages extends JFrame{
int i;
public DrawImages() {
JButton btnNewButton = new JButton("New button");
i = 0;
getContentPane().add(btnNewButton, BorderLayout.SOUTH);
setMinimumSize(new Dimension(1000,150));
final JPanel panel = new JPanel();
panel.setSize(995, 145);
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
final JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 46, 14);
panel.add(lblNewLabel);
btnNewButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent paramActionEvent) {
JPanel panel_1 = new JPanel();
//getContentPane().add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(null);
JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg"));
imagelable.setBounds(70, 5, 105, 65);
panel_1.add(imagelable);
JLabel lblNewLabel_4 = new JLabel("Up Label");
lblNewLabel_4.setBounds(5, 5, 65, 35);
panel_1.add(lblNewLabel_4);
JLabel lblNewLabel_2 = new JLabel("Down Label");
lblNewLabel_2.setBounds(5, 25, 65, 65);
panel_1.add(lblNewLabel_2);
lblNewLabel.setText(""+i);
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
panel.add(panel_1);
i++;
}
});
panel.setMinimumSize(new Dimension(995,150));
}
public static void main(String[]args)
{
DrawImages drawImages = new DrawImages();
drawImages.setVisible(true);
}
}
The problem is with the statement:
panel_1.setLayout(null);
panel_1 doesn't have any preferred size so will not appear (or will appear as a tiny dot).
Swing was designed to use layout managers. You could use GridLayout in this particular case.
Read: Doing Without a Layout Manager
I agree with Reimeus. Just to test your code, I used
panel_1.setLayout(new FlowLayout());
And I could see the panels being added without calling repaint() on the parent panel.
Thanks for your answers but my problem is I added third arguman in every circle:
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
so my panel get bigger and bigger (event biger than my monitor) so the correct is:
panel_1.setBounds(5+170*i, 5, 170, 70);