GridBagLayout Java - java

Hi again i've put in my original code just to let you see what i was talking about for the GridBagConstrainsts thats i was trying to put each image to be stuck to the south of the panel immediately next to each other
package prototype;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
//Declare the class which extends JFrame and
//implements ActionListener to enable bottons to respond whenever clicked or selected
public class Master extends JFrame implements ActionListener {
//create the bottons visible by the user
JButton check = new JButton("");
JButton playList = new JButton("");
JButton update = new JButton("");
JButton quit = new JButton("");
JCheckBox tick = new JCheckBox("Tick");
JPanel top = new JPanel();
public static void main(String[] args) {
//declare object of the class
Master jf = new Master();
}
public Master() {
setLayout(new BorderLayout());
setSize(1050, 400);
setTitle("Master");
// close application only by clicking the quit button
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//show the frame in the middle of the screen when run
setLocationRelativeTo(null);
top.add(new JLabel("Select an option by clicking one of the buttons below"));
add("North", top); // add the text above to the upper part of the frame (North)
JPanel bottom = new JPanel();
bottom.setLayout(new GridBagLayout());
bottom.add(check);
check.addActionListener(this);
bottom.add(playList);
playList.addActionListener(this);
bottom.add(update);
update.addActionListener(this);
bottom.add(quit);
quit.addActionListener(this);
add("South", bottom);
//make the frame non resizable but visible
setResizable(true);
setVisible(true);
try{
Image img = ImageIO.read(getClass().getResource("gui/Exit.png"));
Image resize = img.getScaledInstance(290, 180, 18);
quit.setIcon(new ImageIcon(resize));
img = (bottom, new JLabel("NAME"), 0,0,1,1, GridBagConstraints.SOUTH);
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/Untitled.png"));
Image resize = img.getScaledInstance(290, 180, 18);
check.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/CPL.png"));
Image resize = img.getScaledInstance(290, 180, 18);
playList.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/UpdateLib.png"));
Image resize = img.getScaledInstance(290, 180, 18);
update.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == check) {
new CheckLibrary();
} else if (e.getSource() == update) {
new UpdateLibrary();
} else if (e.getSource() == quit) {
System.exit(0);
} else if (e.getSource() == playList) {
new CreatePlaylist();
}
}
}

For that purposes you need to use anchor and weighty properties of GridBagConstraints.
In next example I set JTextField to the south:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Example extends JFrame {
public Example (){
JTextField f = new JTextField(20);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.SOUTHEAST;
c.weighty = 1;
add(f,c);
}
public static void main(String...strings ){
Example e = new Example();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.pack();
e.setLocationRelativeTo(null);
e.setVisible(true);
}
}
If you need to fill all horizontal space by component add next :
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
For Image you can use JLabel instead of JTextField in my example :
JLabel l = new JLabel(new ImageIcon(getClass().getResource(PATH_TO_IMAGE)));

You cannot add an image directly to a JPanel. What you can do instead is to set the image to be the image icon of a JPanel or JLabel and add that to whatever you're trying to make.

Related

How to put a panel from different class on a frame without disposing off frame

I am doing a project of computer shop management where i have many frames and panels. I have a class named admin panel which contains the frame which further has some buttons i.e : home, about us, add product etc.
Now I want to launch a new panel inside the frame as the button ADD PRODUCT is clicked but the code for the panel should be from different class like a class named addProduct in the same package , How can i do that?
Here you can see all the buttons
I have been successful in launching a panel from different class on the same frame but the problem is that a new frame is launched and I don't wanna do that.
ADMIN PANEL CODE:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class adminPanel implements ActionListener {
public static final Font MY_FONT = new Font("Ubuntu Mono", Font.BOLD, 20);
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
JButton admin = new JButton("Administrator Login");
JButton employee = new JButton("Employee Login");
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
ImageIcon image = new ImageIcon("C:\\Users\\faroo\\Desktop\\car sales stock\\ComputerImage.jpg");
Image scaledImage = image.getImage().getScaledInstance(screensize.width, screensize.height, Image.SCALE_SMOOTH);
JLabel backgroundImage;
JButton[] buttons = new JButton[10];
String[] dropDown = new String[]{
"Hi", "Hello"
};
JList list = new JList(dropDown);
adminPanel() {
//Frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(screensize.width, screensize.height);
frame.setLocation((screensize.width / 2) - (frame.getWidth() / 2), (screensize.height) / 2 - (frame.getHeight() / 2));
frame.setLayout(null);
//IMAGE BACKGROUND
image = new ImageIcon(scaledImage);
backgroundImage = new JLabel(image);
backgroundImage.setBounds(0, 0, screensize.width, screensize.height);
//PANEL 1
panel1.setBounds(screensize.width / 2 - 485, 120, 970, 42);
panel1.setBackground(new Color(223, 223, 223));
panel1.setLayout(new FlowLayout(FlowLayout.LEADING));
//BUTTON: HOME + ABOUT US + ADD PRODUCT + REMOVE PRODUCT +SALES DETAILS +SAlES ORDER
buttons[0] = new JButton("HOME");
buttons[1] = new JButton("ABOUT US");
buttons[2] = new JButton("ADD PRODUCT");
buttons[3] = new JButton("REMOVE PRODUCT");
buttons[4] = new JButton("SALES ORDER");
buttons[5] = new JButton("SALES DETAILS");
buttons[6] = new JButton("LOG OUT");
for (int i = 0; i <= 6; i++) {
buttons[i].setFont(MY_FONT);
buttons[i].setFocusable(false);
buttons[i].setBackground(new Color(61, 94, 148));
buttons[i].setForeground(new Color(223, 223, 223));
panel1.add(buttons[i]);
buttons[i].addActionListener(this);
}
frame.getContentPane().add(panel1);
frame.getContentPane().add(backgroundImage);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i <= 6; i++) {
if (e.getSource() == buttons[i]) {
for (int j = 0; j <= 6; j++) {
buttons[j].setBackground(new Color(61, 94, 148));
}
buttons[i].setBackground(new Color(69, 89, 119));
}
}
if (e.getSource() == buttons[2]) {
addProduct asd = new addProduct();
}
}
}
addProduct CLASS CODE:
package carsalessystem;
import java.awt.Color;
import javax.swing.JPanel;
public class addProduct extends adminPanel{
addProduct(){
JPanel panel2 = new JPanel();
frame.dispose();
panel2.setBackground(Color.darkGray);
panel2.setBounds(panel1.getLocation().x,panel1.getLocation().y+42,970,800);
frame.add(panel2);
frame.add(backgroundImage);
frame.setVisible(true);
}
}

How to print a image on a contentpane(JPanel) in java swing

In the main class Practice extends JFrame, there are three classes UpperPanel, CenterPanel and LowerPanel that extend JPanel.
I'm going to put buttons on UpperPanel and LowerPanel, and put a image on CenterPanel, and print it in one frame.
However, when the image prints out, three Panels aren't printed. and when three Panels print out, the image isn't printed.
I think the problem is setContentPane(new ImagePanel()); when I enter this code (in CenterPanel), Only images are printed. The rest of the panels(Upper, Center, Lower) are not output.
(I have created a separate image output class(ImagePanel extends JPanel), but It's okay to delete this class. But I want to use paintComponent(Graphics g).
I'm sorry for my poor English, and Thank you for reading it
please help me
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Practice extends JFrame {
public int width = 480;
public int height = 720;
public Practice() {
setTitle("20201209");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
setSize(width,height);
c.add(new UpperPanel());
c.add(new CenterPanel());
c.add(new LowerPanel());
setVisible(true);
}
class UpperPanel extends JPanel {
public UpperPanel() {
JPanel UpperPanel = new JPanel();
UpperPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 25));
UpperPanel.setBackground(Color.MAGENTA);
UpperPanel.setBounds(0, 0, 480, 100);
getContentPane().add(UpperPanel);
JButton btnEnlarge = new JButton("1");
btnEnlarge.setFont(new Font("궁서체", Font.PLAIN, 20));
btnEnlarge.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnEnlarge);
JButton btnReduce = new JButton("2");
btnReduce.setFont(new Font("바탕체", Font.ITALIC, 20));
btnReduce.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnReduce);
JButton btnFit = new JButton("3");
btnFit.setFont(new Font("돋움체", Font.BOLD, 20));
btnFit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnFit);
}
}
class CenterPanel extends JPanel{
public CenterPanel() {
JPanel CenterPanel = new JPanel();
CenterPanel.setLayout(null);
CenterPanel.setBackground(Color.YELLOW);
CenterPanel.setBounds(0, 100, 480, 500);
CenterPanel.setOpaque(true);
getContentPane().add(CenterPanel);
setContentPane(new ImagePanel()); // when I enter this code, Only images are printed. The rest of the panels(Upper, Center, Lower) are not output
}
}
class ImagePanel extends JPanel { //this class is for image printing on CenterPanel
private ImageIcon icon = new ImageIcon("images/1771211.jpg");
private Image img = icon.getImage();
public void paintComponent(Graphics g) { //I want to use this code
super.paintComponent(g);
g.drawImage(img, 10, 110, this);
}
}
class LowerPanel extends JPanel {
public LowerPanel() {
JPanel LowerPanel = new JPanel();
LowerPanel.setLayout(null);
LowerPanel.setBackground(Color.BLACK);
LowerPanel.setBounds(0, 600, 480, 120);
getContentPane().add(LowerPanel);
getContentPane().add(new MyButton());
}
}
class MyButton extends JLabel{ //this class is for a Button on LowerPanel
MyButton(){
JButton btn = new JButton("4");
btn.setBounds(10, 610, 460, 100);
btn.setHorizontalAlignment(SwingConstants.CENTER);
btn.setVerticalAlignment(SwingConstants.CENTER);
btn.setFont(new Font("돋움체", Font.BOLD, 50));
btn.setBackground(Color.WHITE);
btn.setForeground(Color.RED);
btn.setOpaque(true);
getContentPane().add(btn);
}
}
public static void main(String[] args) {
new Practice();
}
}
Don't extend JFrame class unnecessarily
Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
Call JFrame#pack() before setting the frame to visible
All Swing components should be called on the EDT via SwingUtilities.invokeLater
Here is a small example of what you want to achieve
TestApp.java:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApp {
BufferedImage image;
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load image
try {
image = ImageIO.read(new URL("https://i.stack.imgur.com/XNO5e.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
// upper panel
JPanel upperPanel = new JPanel(); // JPanels use FlowLayout by default
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
upperPanel.add(button1);
upperPanel.add(button2);
upperPanel.add(button3);
// center panel
JPanel centerPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
};
// lower panel
JPanel lowerPanel = new JPanel();
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
lowerPanel.add(button4);
lowerPanel.add(button5);
lowerPanel.add(button6);
frame.add(upperPanel, BorderLayout.NORTH); // JFrame uses BorderLayout by default
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(lowerPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}

Using one button to change the color of multiple JPanels

So i have three panels that i have three different buttons for to change them each to their respective colors. I need to add a fourth button that will return all three panels to their original default light gray color. I add this "reset" button and it only changes the first panel back. What am i doing wrong?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel;
private JPanel whitePanel;
private JPanel bluePanel;
public static void main(String[] args)
{
PanelDemo gui = new PanelDemo();
gui.setVisible(true);
}
public PanelDemo()
{
super("Panel Demonstration");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new GridLayout(1, 3));
redPanel = new JPanel();
redPanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(redPanel);
whitePanel = new JPanel();
whitePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(whitePanel);
bluePanel = new JPanel();
bluePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(bluePanel);
add(biggerPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(this);
buttonPanel.add(redButton);
JButton whiteButton = new JButton("White");
whiteButton.setBackground(Color.WHITE);
whiteButton.addActionListener(this);
buttonPanel.add(whiteButton);
JButton blueButton = new JButton("Blue");
blueButton.setBackground(Color.BLUE);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
JButton resetButton = new JButton("Reset");
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset"))
redPanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
bluePanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
whitePanel.setBackground(Color.LIGHT_GRAY);
else
System.out.println("Unexpected error.");
}
}
Here was your problem. You had if else's on each panel for the reset. Compare the code below to what you have. It was just a simple logic issue.
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset")) {
redPanel.setBackground(Color.LIGHT_GRAY);
bluePanel.setBackground(Color.LIGHT_GRAY);
whitePanel.setBackground(Color.LIGHT_GRAY);
}
else
System.out.println("Unexpected error.");
And a couple of suggestions.
Don't extend JFrame. Just use an instance of it. It's better technique.
Put the following as the last statement in your constructor. It will center the panel on your screen.
setLocationRelativeTo(null);
// or when using a frame instance.
frame.setLocationRelativeTo(null);

How do I get my JButton to both switch the JPanel and close the JFrame?

I've managed to get the JButton buttonOne in class Database to switch panels, but at the same time it's opening a new JFrame to do this. How can I change it so it just changes the JFrame panel without having to open another JFrame? I have a feeling I could do this if I could return both JPanel and JFrame but I don't know how to do so. Thanks for any help :
First class, with the JFrame and the JPanel that is being switched to on click of 'buttonOne' :
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDatabaseFarme;
import javax.swing.JLabel;
public class Database{
//Running the GUI
public static void main(String[] args) throws IOException {
Database gui2 = new Database();
gui2.mainPanel();
}
JDatabaseFarme mainPanel() throws IOException {
// GridBagLayout/Constraint
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
final JDatabaseFarme DatabaseFarme = new JDatabaseFarme("Lohn Jocke and the Quest for Qualia"); //Had to set DatabaseFarme to final for the action listener
//JPanel panel = new JPanel(new GridBagLayout()); (??)
final JComponent panel = new JLabel(new ImageIcon(ImageIO.read(new File("res/FinalBG.png")))); //Had to set panel to final for the action listener
panel.setLayout(new GridBagLayout());
////// Creating JButtons/Icons for the buttons ////
BufferedImage buttonIcon = ImageIO.read(new File("res/PlayGame.png"));
JButton button = new JButton ("", new ImageIcon(buttonIcon));
BufferedImage buttonIcon2 = ImageIO.read(new File("res/Scoreboard.png"));
JButton buttonTwo = new JButton ("", new ImageIcon(buttonIcon2));
BufferedImage buttonIcon3 = ImageIO.read(new File("res/SQLs.png"));
JButton buttonThree = new JButton ("",new ImageIcon(buttonIcon3));
// Scoreboard button ActionListener
buttonThree.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//removed some code from here
try {
panel.setVisible(false);
SQLsPanel a = new SQLsPanel();
JComponent SQLsPanel = a.SQLsPanel();
DatabaseFarme.add(SQLsPanel);
DatabaseFarme.getContentPane().add(BorderLayout.CENTER, SQLsPanel);
SQLsPanel.setVisible(true);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
////// Creating/adding button rollover images /////
BufferedImage buttonIcon1b = ImageIO.read(new File("res/PlayGameHigh.png"));
button.setRolloverIcon(new ImageIcon(buttonIcon1b));
BufferedImage buttonIcon2b = ImageIO.read(new File("res/ScoreboardHigh.png"));
buttonTwo.setRolloverIcon(new ImageIcon(buttonIcon2b));
BufferedImage buttonIcon3b = ImageIO.read(new File("res/SQLsHigh.png"));
buttonThree.setRolloverIcon(new ImageIcon(buttonIcon3b));
// Setting up GridBagConstraints for each JButton
gbc.weightx=1;
gbc.weighty=0;
gbc.gridx=0;
gbc.gridy=0;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(button, gbc); //PLAY GAME
gbc.weightx=1;
gbc.weighty=0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx=0;
gbc.gridy=1;
panel.add(buttonTwo,gbc); //SCOREBOARD
gbc.weightx=1;
gbc.weighty=0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx=0;
gbc.gridy=2;
panel.add(buttonThree,gbc); //SQLS
// JDatabaseFarme settings
DatabaseFarme.add(panel);
DatabaseFarme.getContentPane().add(BorderLayout.CENTER, panel);
DatabaseFarme.setSize(860,500);
DatabaseFarme.setLocationRelativeTo(null);
DatabaseFarme.setDefaultCloseOperation(JDatabaseFarme.EXIT_ON_CLOSE);
DatabaseFarme.setResizable(false);
DatabaseFarme.setVisible(true);
// JButton icon details
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
buttonTwo.setBorder(BorderFactory.createEmptyBorder());
buttonTwo.setContentAreaFilled(false);
buttonThree.setBorder(BorderFactory.createEmptyBorder());
buttonThree.setContentAreaFilled(false);
return DatabaseFarme;
}
}
My second class, it contains the JButton that needs to change panel and close the JDatabaseFarme :
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDatabaseFarme;
import javax.swing.JLabel;
public class SQLsPanel {
JComponent SQLsPanel() throws IOException {
final JComponent SQLsPanel = new JLabel(new ImageIcon(ImageIO.read(new File("res/HowToPlayBG.png"))));
SQLsPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
BufferedImage buttonOneIcon = ImageIO.read(new File("res/Database.png"));
JButton buttonOne = new JButton("",new ImageIcon(buttonOneIcon));
BufferedImage buttonOneIconB = ImageIO.read(new File("res/DatabaseHigh.png"));
buttonOne.setRolloverIcon(new ImageIcon(buttonOneIconB));
buttonOne.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
SQLsPanel.setVisible(false);
try {
Database passme = new Database();
JDatabaseFarme DatabaseFarmeA = passme.mainPanel();
DatabaseFarmeA.add(SQLsPanel);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
gbc.weighty = 1;
gbc.weightx = 1;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.PAGE_END;
SQLsPanel.add(buttonOne, gbc);
buttonOne.setBorder(BorderFactory.createEmptyBorder());
buttonOne.setContentAreaFilled(false);
return SQLsPanel;
}
}
Try the following:
final JFrame frame = new JFrame("Lohn Jocke and the Quest for Qualia"); //Had to set frame to final for the action listener
final String name = frame.getName();
Add the variable 'name' just below where you declare the JFrame.
// JFrame settings
frame.add(panel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(860,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
if(Frame.getFrames().length > 1){
Frame[] f = Frame.getFrames();
for(Frame frames : f){
if(!frames.getName().equals(name)){
frames.dispose();
}
}
}
Add this below where you set the JFrame settings.
what happens is when you call this
MainMenu passme = new MainMenu();
From the InstructionsPanel you are creating a new JFrame from your class constructor in addition to the current frame you already have(Hence why you end up with 2). what I have tried to do is get the name of your new Frame you are creating(with the name variable), then using the loop at the bottom wipe all other Frames away leaving you with the new one with which to display your Panel.(Frame.getFrames() returns a list of all frames, I then iterate over removing all the ones that aren't needed)
You may want to tweak it if you add more JFrames in future but hopefully this will be somewhat effective for you for now at least.(i have tried to replicate your code with dummy images to grasp at the problem for this 'fix' so apologies if I have misunderstood the issue here )
Hope this helps.

Centering image in a JFrame?

I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Categories