What I'm trying to do is overwriting two panels, where I am Inserting an Image in the background panel through the use of a JLabel, and I want another smaller panel to appear on that same background Image! Here is what I have written:
import javax.swing.*;
import javax.swing.text.html.ImageView;
import java.awt.*;
public class addImage extends JFrame {
private JLabel label;
private ImageIcon Image;
private JButton b;
private JPanel panel1;
private JPanel panel2;
private JLayeredPane layerpanel;
public addImage() {
// JFRame
super("First Time adding Image");
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 400);
// JLabel containing Image
Image = new ImageIcon(getClass().getResource("image1.jpg"));
// Adding Image in JLabel
label = new JLabel(Image);
// Adding Label to panel1
panel1 = new JPanel();
panel1.add(label);
// JPanel2
panel2 = new JPanel();
panel2.setBackground(Color.darkGray);
panel2.setPreferredSize(new Dimension(200, 200));
panel2.setOpaque(true);
// LAyeredPane adding both panels
layerpanel = new JLayeredPane();
layerpanel.setLayout(new BorderLayout());
layerpanel.add(panel1, new Integer(0), 0);
layerpanel.add(panel2, new Integer(1), 1);
add(layerpanel);
}
public static void main(String[] args) {
new addImage();
}
}
After executing the piece of code Im not getting any output except the empty frame!
I am getting these errors :
Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
at java.awt.BorderLayout.addLayoutComponent(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at javax.swing.JLayeredPane.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at addImage.<init>(addImage.java:45)
at addImage.main(addImage.java:53)
I have checked all the question related but still I have not been able to find the solution!!!!
Any kind of help will be appreciated ! Thank you
You're problem is here:
layerpanel.setLayout(new BorderLayout());
layerpanel.add(panel1, new Integer(0), 0);
layerpanel.add(panel2, new Integer(1), 1);
and it's not helped by
setLayout(null);
The JLayeredPane now requires that you pass it one of the valid constraints for BorderLayout (like BorderLayout.NORTH).
Having said that, I'm not sure what you hope to achieve doing this.
You could get the same effect by using a CardLayout with a lot less mess, see How to Use CardLayout for more details
I can "replicate" your desired output using something like...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class AddImage extends JFrame {
private JLabel label;
private ImageIcon Image;
private JButton b;
private JPanel panel1;
private JPanel panel2;
private JLayeredPane layerpanel;
public AddImage() {
// JFRame
super("First Time adding Image");
setLayout(new BorderLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 400);
// JLabel containing Image
// Image = new ImageIcon(getClass().getResource("image1.jpg"));
// Adding Image in JLabel
label = new JLabel("Help");
// Adding Label to panel1
panel1 = new JPanel();
panel1.add(label);
// JPanel2
panel2 = new JPanel();
panel2.setBackground(Color.darkGray);
panel2.setPreferredSize(new Dimension(200, 200));
panel2.setOpaque(true);
// LAyeredPane adding both panels
layerpanel = new JLayeredPane();
layerpanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
layerpanel.add(panel1, gbc);
layerpanel.add(panel2, gbc);
layerpanel.setLayer(panel1, new Integer(0));
layerpanel.setLayer(panel2, new Integer(1));
add(layerpanel);
}
public static void main(String[] args) {
new AddImage();
}
}
Related
I have problem with displaying components on my JFrame. I'm closing my current window and opening new one and want to display jLabel on it but nothing is happening. Code is below :
Frame[] nF = DBChooser.getFrames();
nF[0].setVisible(false);
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel ("Processing...");
textLabel.setLayout(null);
pan.setLayout(null);
windoow.setLayout(null);
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
I appreciate any help
Why you need so many setLayout(null); ? I remove them and it worked
public class DBChooser extends Frame {
public static void main(String args[]) {
Frame[] nF = DBChooser.getFrames();
// nF[0].setVisible(false);
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel("Processing...");
// textLabel.setLayout(null);
// pan.setLayout(null);
// windoow.setLayout(null);
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
}
}
It is because you set a null layout to window and panel without specifying any width, lenght or position, either use some LayoutManager or set these properties (eg. bounds). A null LayoutManager means that you need to set everything yourself, because there is nothing (no LayoutManager) that would place your elements automatically. This example uses a BorderLayout, which creates a nice effect:
the code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
JFrame windoow = new JFrame("Processing");
JPanel pan = new JPanel();
windoow.setPreferredSize(new Dimension(400, 150));
pan.setPreferredSize(new Dimension(400, 150));
JLabel textLabel = new JLabel("Processing...");
textLabel.setLayout(null);
pan.setLayout(new BorderLayout());
windoow.setLayout(new BorderLayout());
pan.add(textLabel);
pan.revalidate();
pan.repaint();
windoow.getContentPane().add(pan);
windoow.setLocationRelativeTo(null);
windoow.pack();
windoow.setVisible(true);
}
}
I'm making a restaurant menu program with GUI.
I created 3 JPanels and set Background(Color.white) to one of them.
But java will not display that background color.
What's wrong?
Here is my code
please do not take any attention to foods' price and cardLayout. Not finished with coding.
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"),
box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel(){
setOpaque(true);
setBackground(Color.white);
setLayout(new GridLayout(3,1));
// setBorder();
add(box1);add(box2);add(box3);
setVisible(true);
}
}
class with main method:
import java.awt.BorderLayout;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
public class RestaurantMenu extends JFrame implements ActionListener{
/* private JPanel maindishPanel= new JPanel(),
dessertPanel = new JPanel(),
drinkPanel = new JPanel(),*/
private JPanel leftPanel = new JPanel(),
rightPanel = new JPanel();
private MainDishPanel maindish = new MainDishPanel();
private DessertPanel dessert = new DessertPanel();
private DrinkPanel drink = new DrinkPanel();
private LinkedList<Double>price = new LinkedList<>();
private JButton left = new JButton("previous"),
right = new JButton("next");
public int page =1;
private JLabel pageLabel = new JLabel(String.valueOf(page)),
foodTypeLabel = new JLabel();
CardLayout cards;
GridBagLayout grid;
RestaurantMenu(){
setTitle("Main Dish");
GridBagConstraints gbc = new GridBagConstraints();
add(foodTypeLabel, BorderLayout.NORTH);
add(pageLabel, BorderLayout.SOUTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
add(maindish, BorderLayout.CENTER);
grid = new GridBagLayout();
leftPanel.setLayout(grid); leftPanel.add(left);
rightPanel.setLayout(grid); rightPanel.add(right);
right.addActionListener(this);
left.addActionListener(this);
//cards = new CardLayout();
/*cards = (CardLayout)maindishPanel.getLayout();
cards.show(maindishPanel,"Main Dish");*/
setVisible(true);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==right)
cards.next(this);
if(e.getSource()==left)
cards.previous(this);
}
public static void main (String []args){
RestaurantMenu rm = new RestaurantMenu();
}
}
I don't get any error. Background color just won't be changed to white.
RestaurantMenu class can be looked like a spaghetti code or something strange
because I have plenty things to do with that class.
Inside your MainDishPanel you need to set the background color for the JCheckBox to white, or you can just setOpaque to false on your JCheckBox
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class MainDishPanel extends JPanel {
JCheckBox box1 = new JCheckBox("Hamburger 5 dollars"), box2 = new JCheckBox("Pizza 5 dollars"),
box3 = new JCheckBox("French Hot dog 5 dollars");
MainDishPanel() {
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new GridLayout(3, 1));
box1.setBackground(Color.WHITE); // or box1.setOpaque(false);
box2.setBackground(Color.WHITE);
box3.setBackground(Color.WHITE);
add(box1);
add(box2);
add(box3);
setVisible(true);
}
}
I am creating a JFrame that contains a JPanel with a grid of buttons. Everything works fine but I then want to add a JLabel above the panel of buttons but the label never appears. It does appear if I don't use BoxLayout, though. Any help is appreciated.
The first code part below is my JFrame class:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame {
private static final long serialVersionUID = 1L;
Panel panel = new Panel();
Dimension frameDim = new Dimension(1000, 1000);
Dimension labelDim = new Dimension(100, 20);
Box box = new Box(BoxLayout.Y_AXIS);
JLabel label = new JLabel("Tic Tac Toe");
JPanel pane = new JPanel();
public Frame() {
pane.add(label);
pane.setPreferredSize(labelDim);
pane.setMinimumSize(labelDim);
add(pane);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
add(box);
setTitle("Tic Tac Toe");
setSize(frameDim);
setMinimumSize(frameDim);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
The code below is my JPanel class with buttons:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel extends JPanel {
private static final long serialVersionUID = 2L;
private int i;
JButton[] button = new JButton[9];
GridLayout layout = new GridLayout(3, 3);
Dimension dim = new Dimension(500, 500);
public Panel() {
for (i = 0; i<9; i++) {
button[i] = new JButton();
add(button[i]);
}
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
setLayout(layout);
}
}
The last code part below is the Main class:
public class RunGame {
public static void main(String[] args) {
new Frame();
}
}
add(box);
This is adding the label direct to the JFrame, the content pane of which is laid out using a BorderLayout. The default when adding to a component to a border layout without any constraint is the CENTER, which can only display a single component. To fix it use:
pane.add(box);
you can use the BorderLayout when adding your label into Pane into the Frame and remove that box thing as below
public Frame()
{
//create label and add it to the frame
JLabel label = new JLabel("Tic Tac Toe");
label.setHorizontalAlignment( JLabel.CENTER );
add(label, BorderLayout.NORTH);
//create buttonsPanel and add it to the frame
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout(3, 3));
for (int i = 0; i < 9; i++)
{
buttons.add(new JButton(""+i));
}
add(buttons, BorderLayout.CENTER);
//setup the title, other properties for the frame etc..
setTitle("Tic Tac Toe");
setSize(1000, 1000);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
hope this helps better :)
Hey guys my buttons and textarea will not display on JFrame when compiled, i have tried everything and searched this site but no luck. Any help would be greatly appreciated. Due to them not letting me post without more detail i am just adding this part so i can hit the submit button.
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class DataManager extends JFrame {
private String students[] = {"John Smith","Ken Hanson","Michael Li","John Andersen","Fiona Harris","Angela Lim","Bob London","Sydney Shield","Tina Gillard",
"Ross Brinns","Scott Cairns","Grant Peterson","David Power","Joshua Kane","Alan Newton","Frady Morgan","Quinn Perth"};
private int english[] = {80,52,71,61,39,62,31,46,60,26,77,40,58,38,94,90,97};
private int maths[] = {60,45,77,90,45,55,66,87,31,42,65,55,80,71,51,55,95};
private int total[];
private JButton sortNameButton;
private JButton sortTotalButton;
private JTextField searchTextField;
private JButton statisticsButton;
private JButton exitButton;
private JTextArea infoTextArea;
private JPanel jPan;
public DataManager() {
super("Data Manager ");
jPan = new JPanel();
sortNameButton = new JButton("Sort By Name");
sortTotalButton = new JButton("Sort By Total");
searchTextField = new JTextField("Search");
statisticsButton = new JButton("Statistics");
exitButton = new JButton("Exit");
infoTextArea = new JTextArea();
setLayout(new BorderLayout());
jPan.add(sortNameButton, BorderLayout.NORTH);
jPan.add(sortTotalButton, BorderLayout.NORTH);
jPan.add(searchTextField, BorderLayout.NORTH);
jPan.add(statisticsButton, BorderLayout.NORTH);
jPan.add(exitButton, BorderLayout.NORTH);
jPan.add(infoTextArea, BorderLayout.CENTER);
}
public static void main(String[] args) {
DataManager frame = new DataManager();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
} // End of main method.
} // End of DataManager class
You add your JButtons to the jPan JPanel but never add the jPan to anything -- it must be added to your JFrame, to this to be seen.
jPan.add(sortNameButton);
jPan.add(sortTotalButton);
jPan.add(searchTextField);
jPan.add(statisticsButton);
jPan.add(exitButton);
jPan.add(infoTextArea);
add(jPan); // don't forget this! ************
Note other problems:
You set the JFrame's layout to BorderLayout -- it's already using BorderLayout
You add components to your jPan JPanel with BorderLayout constants, but it's not using a BorderLayout.
If it were, many buttons would not be seen since many are added to the same BorderLayout position and will cover the previous component added there.
In other words, read the tutorials as you're making wrong assumptions.
Better would be something like:
// setLayout(new BorderLayout());
jPan.setLayout(new BorderLayout());
JPanel northPanel = new JPanel(); // **** to hold buttons
northPanel.add(sortNameButton);
northPanel.add(sortTotalButton);
northPanel.add(searchTextField);
northPanel.add(statisticsButton);
northPanel.add(exitButton);
jPan.add(northPanel, BorderLayout.PAGE_START);
jPan.add(infoTextArea, BorderLayout.CENTER);
I'm currently developing a small utility with the following GUI:
Right now i have a container (JPanel) with the BorderLayout layout that holds everything in place. The i have another 2 JPanels placed on BorderLayout.NORTH and BorderLayout.SOUTH respectively, each whith the GridLayout (2 columns by 1 row). The table is on the main container placed at the CENTER of it.
Do you think this is the best approach? I'm having a rough time dealing with spacing between the components and the borders of the frame.
Right now i have this code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class GUI extends JFrame {
private JButton loadFileBtn = new JButton("Load File");
private JButton generateReportBtn = new JButton("Generate Report");
private JButton exitBtn = new JButton("Exit");
private JLabel fileNameLbl = new JLabel("File Name Here");
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMI = new JMenu("File");
private JMenuItem openFileMenu = new JMenuItem("Open File");
private JSeparator separator = new JSeparator();
private JMenuItem exitMenu = new JMenuItem("Exit");
private JMenu reportMI = new JMenu("Report");
private JMenuItem generateReportMenu = new JMenuItem("Generate Report");
private JMenu helpMI = new JMenu("Help");
private JMenuItem aboutMenu = new JMenuItem("About");
private JTable table = new JTable(5, 2);
private JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
private JPanel panel1 = new JPanel(new BorderLayout());
private JPanel panel2 = new JPanel(new GridLayout(1, 2));
private JPanel panel3 = new JPanel(new GridLayout(1, 2));
public GUI() {
super("Sample GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(300, 300));
setResizable(false);
setLayout(new BorderLayout(10, 10));
fileMI.add(openFileMenu);
fileMI.add(separator);
fileMI.add(exitMenu);
reportMI.add(generateReportMenu);
helpMI.add(aboutMenu);
menuBar.add(fileMI);
menuBar.add(reportMI);
menuBar.add(helpMI);
setJMenuBar(menuBar);
panel1.add(table, BorderLayout.CENTER);
panel2.add(fileNameLbl);
panel2.add(loadFileBtn);
panel3.add(generateReportBtn);
panel3.add(exitBtn);
mainPanel.add(panel2, BorderLayout.NORTH);
mainPanel.add(panel1, BorderLayout.CENTER);
mainPanel.add(panel3, BorderLayout.SOUTH);
add(mainPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI app = new GUI();
app.setVisible(true);
}
});
}
}
What do you think would be the best approach to do this?
Any help would be appreciated. Thanks.
UPDATE:
Right now, i have the following GUI
I want the components to space away from the borders evenly, like in the mockup.
2 things you can use to make this happen:
Use BorderFactory.createEmptyBorder(int, int, int, int)
Use the 4-args constructor of GridLayout
There are other LayoutManager's which can bring the same functionality (like GridBagLayout, or using nested BorderLayout), but if you feel comfortable with the current LayoutManager's, there is no imperious need to change to those. The way you did is also acceptable.
You might consider wrapping the table in a JScrollPane to make it nicer, with headers and scrollbars if ever needed.
Small example code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class GUI extends JFrame {
private JButton loadFileBtn = new JButton("Load File");
private JButton generateReportBtn = new JButton("Generate Report");
private JButton exitBtn = new JButton("Exit");
private JLabel fileNameLbl = new JLabel("File Name Here");
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMI = new JMenu("File");
private JMenuItem openFileMenu = new JMenuItem("Open File");
private JSeparator separator = new JSeparator();
private JMenuItem exitMenu = new JMenuItem("Exit");
private JMenu reportMI = new JMenu("Report");
private JMenuItem generateReportMenu = new JMenuItem("Generate Report");
private JMenu helpMI = new JMenu("Help");
private JMenuItem aboutMenu = new JMenuItem("About");
private JTable table = new JTable(5, 2);
private JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
private JPanel panel1 = new JPanel(new BorderLayout());
private JPanel panel2 = new JPanel(new GridLayout(1, 2, 10, 10));
private JPanel panel3 = new JPanel(new GridLayout(1, 2, 10, 10));
public GUI() {
super("Sample GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(300, 300));
setResizable(false);
setLayout(new BorderLayout(10, 10));
fileMI.add(openFileMenu);
fileMI.add(separator);
fileMI.add(exitMenu);
reportMI.add(generateReportMenu);
helpMI.add(aboutMenu);
menuBar.add(fileMI);
menuBar.add(reportMI);
menuBar.add(helpMI);
setJMenuBar(menuBar);
panel1.add(table, BorderLayout.CENTER);
panel2.add(fileNameLbl);
panel2.add(loadFileBtn);
panel3.add(generateReportBtn);
panel3.add(exitBtn);
mainPanel.add(panel2, BorderLayout.NORTH);
mainPanel.add(panel1, BorderLayout.CENTER);
mainPanel.add(panel3, BorderLayout.SOUTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(mainPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI app = new GUI();
app.setVisible(true);
}
});
}
}
In the past, I have found that using MigLayout, solves all my problems
Here's how I would arrange your GUI. This is just one way. It's not the only way.
The JTable goes inside of a JScrollPane.
Button2 and Button3 go inside of a button JPanel with a FlowLayout.
Label and Button1 go inside of a label JPanel with a FlowLayout.
File, Report, and Help are JMenuItems on a JMenuBar.
The main JPanel has a BoxLayout with a Y_AXIS orientation.
Add the label JPanel, the JScrollPane, and the button JPanel to the main JPanel.
The best way is to create a GUI is to code in a way you and others will understand . Take a look at this Guide to Layout Managers. You can use different layout managers for different components. This will help you setting correct spacing.
If your problem is just the spacing around the components, set its Insets.