Sorry if its an obvious question.I have been trying to switch panels in the same window using cardlayout.But when i run my application nothing happens.
System.out.println(mntmBookingStatus);
the above statement does get printed on console.but not able to make out why cards arent switching when i click on menuitem "booking status" and "invoice entry".
public class StartDemo {
private JFrame frame;
private JPanel cards = new JPanel(new CardLayout());
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StartDemo window = new StartDemo();
window.initialize();
window.frame.pack();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 772, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
// main menu
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
// mainmenuoption-1
mnNewMenu = new JMenu("Entries");
menuBar.add(mnNewMenu);
// option-1 items
mntmBookingStatus = new JMenuItem("Booking Status");
mnNewMenu.add(mntmBookingStatus);
mntmBookingStatus.addActionListener(new MenuListenerAdapter());
mntmInvoiceEntry = new JMenuItem("Invoice Entry");
mnNewMenu.add(mntmInvoiceEntry);
mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());
StartDemo demo = new StartDemo();
demo.addComponentToPane(frame.getContentPane());
}
public void addComponentToPane(Container pane) {
JPanel booking_status = new JPanel();
JPanel invoice_entry = new JPanel();
JPanel customer_ledger = new JPanel();
JPanel create_user = new JPanel();
try {
JPanelWithBackground panelWithBackground = new JPanelWithBackground(
"D:\\Kepler Workspace\\WEDemo\\images\\abc.jpg");
cards.add(panelWithBackground, "name_282751308799");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the layout code for all the panels is written here.
//its to big to post here
cards.add(booking_status, BOOKINGPANEL);
cards.add(invoice_entry, INVOICEPANEL);
cards.add(customer_ledger, CUSTOMERLEDGER);
cards.add(create_user, CREATEUSER);
pane.add(cards, BorderLayout.CENTER);
}
public class MenuListenerAdapter implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout c = (CardLayout) (cards.getLayout());
if (e.getSource() == mntmBookingStatus) {
c.show(cards, BOOKINGPANEL);
System.out.println(mntmBookingStatus);
} else if (e.getSource() == mntmInvoiceEntry) {
c.show(cards, INVOICEPANEL);
System.out.println(mntmInvoiceEntry);
}
}
This is my JPanelWithBackground class
public class JPanelWithBackground extends JPanel {
private Image backgroungImage;
private Image scaledBackgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroungImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
// Draw the backgroung image
g.drawImage(backgroungImage, 0, 0,getWidth(),getHeight(),null);
}
It's these two lines right here
StartDemo demo = new StartDemo();
demo.addComponentToPane(frame.getContentPane());
Since your initialize() method isn't static I think it's safe to assume that you instantiate youe StartDemo again in the main method. In that case, the above code truly is your problem and would totally explain why it doesn't work. Just do this
//StartDemo demo = new StartDemo(); <-- get rid of this.
addComponentToPane(frame.getContentPane());
Tested with code additions only to get it running. Also please not my comments above. setVisible(true) generally is the last thing you should do after adding all components.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartDemo {
private JFrame frame;
private JPanel cards = new JPanel(new CardLayout());
JMenuBar menuBar;
JMenu mnNewMenu;
JMenuItem mntmBookingStatus;
JMenuItem mntmInvoiceEntry;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new StartDemo().initialize();
}
});
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 772, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// main menu
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
// mainmenuoption-1
mnNewMenu = new JMenu("Entries");
menuBar.add(mnNewMenu);
// option-1 items
mntmBookingStatus = new JMenuItem("Booking Status");
mnNewMenu.add(mntmBookingStatus);
mntmBookingStatus.addActionListener(new MenuListenerAdapter());
//StartDemo demo = new StartDemo();
addComponentToPane(frame.getContentPane()); mntmInvoiceEntry = new JMenuItem("Invoice Entry");
mnNewMenu.add(mntmInvoiceEntry);
mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());
frame.setVisible(true);
}
public void addComponentToPane(Container pane) {
JPanel booking_status = new JPanel();
JPanel invoice_entry = new JPanel();
//JPanel customer_ledger = new JPanel();
//JPanel create_user = new JPanel();
try {
JPanelWithBackground panelWithBackground = new JPanelWithBackground(
"/resources/stackoverflow5.png");
cards.add(panelWithBackground, "name_282751308799");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cards.add(booking_status, "booking");
cards.add(invoice_entry, "invoice");
//cards.add(customer_ledger, CUSTOMERLEDGER);
//cards.add(create_user, CREATEUSER);
pane.add(cards, BorderLayout.CENTER);
}
class JPanelWithBackground extends JPanel {
Image img;
public JPanelWithBackground(String path) throws IOException {
img = ImageIO.read(getClass().getResource(path));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
public class MenuListenerAdapter implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout c = (CardLayout) (cards.getLayout());
if (e.getSource() == mntmBookingStatus) {
c.show(cards,"booking");
System.out.println(mntmBookingStatus);
} else if (e.getSource() == mntmInvoiceEntry) {
c.show(cards, "invoice");
System.out.println(mntmInvoiceEntry);
}
}
}
}
Related
The idea is to have one "global" JFrame which I can then add/remove JPanels as needed to make a smooth flowing application. Currently, when I try changing from the first JPanel to the second, the second won't display. My code is below:
Handler (class to run the app):
package com.example.Startup;
import com.example.Global.Global_Frame;
public class Handler
{
public Handler()
{
gf = new Global_Frame();
gf.getAccNum();
gf.setVisible(true);
}
public static void main(String[] args)
{
new Handler();
}
Global_Frame gf = null;
}
public static void main(String[] args)
{
new Handler();
}
Global_Vars gv = null;
Global_Frame gf = null;
}
Global Frame:
package com.example.Global;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.example.FirstRun.AccDetails;
import com.example.FirstRun.FirstTimeRun;
public class Global_Frame extends JFrame
{
private static final long serialVersionUID = 1L;
ActionListener val = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
getUserDetails();
}
};
public Global_Frame()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // get look and feel based on OS
}
catch (ClassNotFoundException ex) // catch all errors that may occur
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (UnsupportedLookAndFeelException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() //run the class's constructor, therefore starting the UI being built
{
initComponents();
}
});
}
public void initComponents()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
revalidate(); // revalidate the elements that will be displayed
repaint(); // repainting what is displayed if going coming from a different form
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
}
public void getAccNum()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
FirstTimeRun panel1 = new FirstTimeRun(val);
add(panel1);
revalidate();
repaint();
pack();
}
public void getUserDetails()
{
getContentPane().removeAll();
resizing(750, 500);
AccDetails panel2 = new AccDetails();
add(panel2);
revalidate();
repaint();
pack();
}
private void resizing(int width, int height)
{
timer = new Timer (10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
getContentPane().removeAll();
setPreferredSize(new Dimension(sizeW, sizeH));
revalidate();
repaint();
pack();
if (!wToggle)
sizeW += 2;
if (!hToggle)
sizeH += 2;
if (toggle)
{
setLocationRelativeTo(null);
toggle = false;
}
else
toggle = true;
if (sizeW == width)
wToggle = true;
if (sizeH == height)
hToggle = true;
if (hToggle && wToggle)
timer.stop();
}
});
timer.start();
}
//variables used for window resizing
private Timer timer;
private int sizeW = 600;
private int sizeH = 400;
private boolean toggle = false;
private boolean wToggle = false;
private boolean hToggle = false;
public int accNum = 0;
}
First Panel:
package com.example.FirstRun;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class FirstTimeRun extends JPanel
{
private static final long serialVersionUID = 1L;
public FirstTimeRun()
{
}
public FirstTimeRun(ActionListener val)
{
initComponents(val);
}
private void initComponents(ActionListener val) // method to build initial view for user for installation
{
pnlStart = new JPanel[1];
btnNext = new JButton();
pnlStart[0] = new JPanel();
btnNext.setText("Next"); // adding text to button for starting
btnNext.setPreferredSize(new Dimension(80, 35)); //positioning start button
btnNext.addActionListener(val);
pnlStart[0].add(btnNext); // adding button to JFrame
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlStart[0]);
}
// objects used in UI
private JPanel[] pnlStart;
private JButton btnNext;
}
Second Panel:
package com.example.FirstRun;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AccDetails extends JPanel
{
private static final long serialVersionUID = 1L;
public AccDetails()
{
accAssets();
}
private void accAssets()
{
// instantiating elements of the GUI
pnlAccDetails = new JPanel[2];
lblWelcome = new JLabel();
lblMain = new JLabel();
for (int i = 0; i < 2; i++)
pnlAccDetails[i] = new JPanel();
lblWelcome.setText("Welcome to Example_App"); // label welcoming user
pnlAccDetails[0].setLayout(new BoxLayout(pnlAccDetails[0], BoxLayout.LINE_AXIS));
pnlAccDetails[0].add(lblWelcome); // adding label to form
lblMain.setText("<html>The following information that is collected will be used as part of the Example_App process to ensure that each user has unique Example_App paths. Please fill in all areas of the following tabs:</html>"); // main label that explains what happens, html used for formatting
pnlAccDetails[1].setLayout(new BorderLayout());
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_START);
pnlAccDetails[1].add(lblMain, BorderLayout.CENTER); //adding label to JFrame
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_END);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlAccDetails[0]);
add(pnlAccDetails[1]);
}
private JLabel lblWelcome;
private JLabel lblMain;
private JPanel[] pnlAccDetails;
}
I have tried using both a CardLayout and the "revalidate();" "repaint();" and "pack();" options and I'm stumped as to why it's not showing. Thanks in advance for any help that can be offered.
EDIT:
While cutting down my code, if the "resizing" method is removed, the objects are shown when the panels change. I would like to avoid having to remove this completely as it's a smooth transition for changing the JFrame size.
#John smith it is basic example of switch from one panel to other panel I hope this will help you to sort out your problem
Code:
package stack;
import java.awt.BorderLayout;
import java.awt.Dimension;
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;
public class RemoveAndAddPanel implements ActionListener{
JFrame frame;
JPanel firstPanel;
JPanel secondPanel;
JPanel controlPanel;
JButton nextButton;
public RemoveAndAddPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.add(new JLabel("FirstPanel"));
firstPanel.setPreferredSize(new Dimension(100,100));
secondPanel = new JPanel();
secondPanel.add(new JLabel("Second panel"));
secondPanel.setPreferredSize(new Dimension(100,100));
nextButton = new JButton("Next panel");
controlPanel = new JPanel();
nextButton.addActionListener(this);
controlPanel.add(nextButton);
frame.setLayout(new BorderLayout());
frame.add(firstPanel,BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(300,100);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == nextButton) {
frame.remove(firstPanel);
frame.add(secondPanel);
nextButton.setEnabled(false);
}
frame.validate();
}
public static void main(String args[]) {
new RemoveAndAddPanel();
}
}
As mentioned in the edit, the problem lay within the resizing method. When the timer stopped, it wouldn't go anywhere, causing the UI to not load. The fix to the code is clearing the screen and adding the call to resizing to the actionlistener. Then adding a call to the next method after:
timer.stop();
Thanks for getting me to remove the mess around it and find the source of the problem #matt & #Hovercraft Full of Eels upvotes for both of you.
The main thing to consider while changing panel in a jframe is the layout, for a body(main) panel to change to any other panel the parent panel must be of type CardLayout body.setLayout(new java.awt.CardLayout());
After that you can now easily switch between panels wiht the sample code below
private void updateViewLayout(final HomeUI UI, final JPanel paneeelee){
final JPanel body = UI.getBody(); //this is the JFrame body panel and must be of type cardLayout
System.out.println("Page Loader Changing View");
new SwingWorker<Object, Object>() {
#Override
protected Object doInBackground() throws Exception {
body.removeAll();//remove all visible panel before
body.add(paneeelee);
body.revalidate();
body.repaint();
return null;
}
#Override
protected void done() {
UI.getLoader().setVisible(false);
}
}.execute();
}
I'm having some problems with my class that I need some help with. The class is supposed to take retrieve a csv.file from the file chooser, and then put the name of the file into a Jlist, but I can't get the JList to print the arraylist that I put the chosen files into. This is the code I've got, so I'd be grateful if you could take a look at it and tell me what I need to change with it in order to get the JList to print the arraylist.
import dao.UserDAO;
import db.DemoDB;
import model.Activity;
import model.DataPoint;
import model.Statistics;
public class LoginGUI1 {
DemoDB DemoDBSingleton = null;
private JTabbedPane tabbedPane = new JTabbedPane();
UserDAO userDao = new UserDAO();
JFrame mainFrame = new JFrame("Välkommen till din app");
JFrame f = new JFrame("User Login");
JLabel l = new JLabel("Användarnamn:");
JLabel l1 = new JLabel("Lösenord:");
JTextField textfieldUsername = new JTextField(10);
JPasswordField textfieldPassword = new JPasswordField(10);
JButton loginButton = new JButton("Logga In");
JFileChooser fc = new JFileChooser();
JMenuBar mb = new JMenuBar();
JList listAct = new JList();
List<Activity> activityList = new ArrayList<Activity>();
List activityList1 = new Vector();
JFrame jf;
JMenu menu;
JMenuItem importMenu, exitMenu;
Activity activity = new Activity();
public LoginGUI1() throws IOException {
DemoDBSingleton = DemoDB.getInstance();
ProgramMainFrame();
}
private void ProgramMainFrame() throws IOException {
mainFrame.setSize(800, 600);
mainFrame.setVisible(true);
mainFrame.setJMenuBar(mb);
mainFrame.getContentPane().setLayout(new BorderLayout());;
tabbedPane.add("Dina Aktiviteter", createViewActPanel());
mainFrame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
tabbedPane.add("Diagram för vald aktivitet", createViewDiagramPanel());
tabbedPane.add("Statistik för vald aktivitet", createViewStatisticsPanel());
tabbedPane.add("Kartbild över vald aktivitet", createViewMapPanel());
JMenuBar mb = new JMenuBar();
menu = new JMenu("Meny");
importMenu = new JMenuItem("Importera aktivitet");
importMenu.addActionListener(importActionListener);
exitMenu = new JMenuItem("Avsluta program");
exitMenu.addActionListener(exitActionListener);
menu.add(importMenu);
menu.add(exitMenu);
mb.add(menu);
mainFrame.setJMenuBar(mb);
/* JPanel listholder = new JPanel();
listholder.setBorder(BorderFactory.createTitledBorder("ListPanel"));
mainFrame.add(listholder);
listholder.setVisible(true);
listholder.setSize(500,400);*/
}
private JPanel createViewActPanel() {
JPanel analogM = new JPanel();
analogM.setBackground(new Color(224, 255, 255));
return analogM;
}
ActionListener importActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int returnValue = fc.showOpenDialog(mainFrame);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file != null)
{
String fileName = file.getAbsolutePath();
Activity activity = null;
try {
activity = new Activity();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
activity.csvFileReader(fileName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
activityList.add(activity);
listAct.setListData(activityList.toArray());
}
}
}
};
public static void main(String[] args) throws IOException {
new LoginGUI();
}
}
There's a lot of context missing, so the best I can do is provide a simple running example which works.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test {
public static void main(String args[]) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList<File> fileList;
private DefaultListModel<File> fileListModel;
public TestPane() {
fileListModel = new DefaultListModel<>();
fileList = new JList(fileListModel);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileListModel.addElement(file);
}
}
});
setLayout(new BorderLayout());
add(new JScrollPane(fileList));
add(addButton, BorderLayout.SOUTH);
}
}
}
I'd highly recommend having a look at How to use lists to get a better understanding of how the API works
What I'm trying to do is to create a desktop application using Swing. I need to add a background image to my frame and also add some buttons on some specific locations which should NOT have their content area filled. So, here is what I've done so far;
public class MainGUI extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGUI window = new MainGUI();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainGUI() {
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initialize();
}
private void initialize() {
JPanel mainPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
g.drawImage(new ImageIcon(ImageIO.read(new File("a.png"))).getImage(), 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
mainPanel.setLayout(new BorderLayout());
JButton btn1 = new JButton();
btn1 .setAlignmentX(Component.CENTER_ALIGNMENT);
btn1 .setContentAreaFilled(false);
btn1 .setBorder(new EmptyBorder(0, 0, 0, 0));
btn1 .setIcon(new ImageIcon("btn1.png"));
JPanel rightButtonPanel = new JPanel();
rightButtonPanel.setLayout(new BoxLayout(rightButtonPanel, BoxLayout.Y_AXIS));
rightButtonPanel.add(btn1);
mainPanel.add(rightButtonPanel, BorderLayout.EAST);
this.setContentPane(mainPanel);
}
}
When I do this, setContentAreaFilled(false) feature does not work. I suppose it's related to the painting but I'm not sure. Can anyone help me with this please?
So I took your code and modified it.
Primarily:
Added btn1.setOpaque(false);
And added rightButtonPanel.setBackground(Color.GREEN);
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class MainGUI extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGUI window = new MainGUI();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initialize();
pack();
}
private void initialize() {
JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
};
mainPanel.setBackground(Color.RED);
mainPanel.setLayout(new BorderLayout());
JButton btn1 = new JButton();
btn1.setAlignmentX(Component.CENTER_ALIGNMENT);
btn1.setContentAreaFilled(false);
btn1.setOpaque(false);
btn1.setBorder(new EmptyBorder(0, 0, 0, 0));
btn1.setText("This is a test");
JPanel rightButtonPanel = new JPanel();
rightButtonPanel.setBackground(Color.GREEN);
rightButtonPanel.setLayout(new BoxLayout(rightButtonPanel, BoxLayout.Y_AXIS));
rightButtonPanel.add(btn1);
mainPanel.add(rightButtonPanel, BorderLayout.EAST);
this.setContentPane(mainPanel);
}
}
This produced
So, it's not the buttons (at least at this point) which are at fault.
So, I changed rightButtonPanel.setBackground(Color.GREEN); to rightButtonPanel.setOpaque(false); and it produced
The idea is to have one "global" JFrame which I can then add/remove JPanels as needed to make a smooth flowing application. Currently, when I try changing from the first JPanel to the second, the second won't display. My code is below:
Handler (class to run the app):
package com.example.Startup;
import com.example.Global.Global_Frame;
public class Handler
{
public Handler()
{
gf = new Global_Frame();
gf.getAccNum();
gf.setVisible(true);
}
public static void main(String[] args)
{
new Handler();
}
Global_Frame gf = null;
}
public static void main(String[] args)
{
new Handler();
}
Global_Vars gv = null;
Global_Frame gf = null;
}
Global Frame:
package com.example.Global;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.example.FirstRun.AccDetails;
import com.example.FirstRun.FirstTimeRun;
public class Global_Frame extends JFrame
{
private static final long serialVersionUID = 1L;
ActionListener val = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
getUserDetails();
}
};
public Global_Frame()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // get look and feel based on OS
}
catch (ClassNotFoundException ex) // catch all errors that may occur
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (UnsupportedLookAndFeelException ex)
{
Logger.getLogger(Global_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() //run the class's constructor, therefore starting the UI being built
{
initComponents();
}
});
}
public void initComponents()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
revalidate(); // revalidate the elements that will be displayed
repaint(); // repainting what is displayed if going coming from a different form
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
}
public void getAccNum()
{
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
FirstTimeRun panel1 = new FirstTimeRun(val);
add(panel1);
revalidate();
repaint();
pack();
}
public void getUserDetails()
{
getContentPane().removeAll();
resizing(750, 500);
AccDetails panel2 = new AccDetails();
add(panel2);
revalidate();
repaint();
pack();
}
private void resizing(int width, int height)
{
timer = new Timer (10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
getContentPane().removeAll();
setPreferredSize(new Dimension(sizeW, sizeH));
revalidate();
repaint();
pack();
if (!wToggle)
sizeW += 2;
if (!hToggle)
sizeH += 2;
if (toggle)
{
setLocationRelativeTo(null);
toggle = false;
}
else
toggle = true;
if (sizeW == width)
wToggle = true;
if (sizeH == height)
hToggle = true;
if (hToggle && wToggle)
timer.stop();
}
});
timer.start();
}
//variables used for window resizing
private Timer timer;
private int sizeW = 600;
private int sizeH = 400;
private boolean toggle = false;
private boolean wToggle = false;
private boolean hToggle = false;
public int accNum = 0;
}
First Panel:
package com.example.FirstRun;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class FirstTimeRun extends JPanel
{
private static final long serialVersionUID = 1L;
public FirstTimeRun()
{
}
public FirstTimeRun(ActionListener val)
{
initComponents(val);
}
private void initComponents(ActionListener val) // method to build initial view for user for installation
{
pnlStart = new JPanel[1];
btnNext = new JButton();
pnlStart[0] = new JPanel();
btnNext.setText("Next"); // adding text to button for starting
btnNext.setPreferredSize(new Dimension(80, 35)); //positioning start button
btnNext.addActionListener(val);
pnlStart[0].add(btnNext); // adding button to JFrame
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlStart[0]);
}
// objects used in UI
private JPanel[] pnlStart;
private JButton btnNext;
}
Second Panel:
package com.example.FirstRun;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AccDetails extends JPanel
{
private static final long serialVersionUID = 1L;
public AccDetails()
{
accAssets();
}
private void accAssets()
{
// instantiating elements of the GUI
pnlAccDetails = new JPanel[2];
lblWelcome = new JLabel();
lblMain = new JLabel();
for (int i = 0; i < 2; i++)
pnlAccDetails[i] = new JPanel();
lblWelcome.setText("Welcome to Example_App"); // label welcoming user
pnlAccDetails[0].setLayout(new BoxLayout(pnlAccDetails[0], BoxLayout.LINE_AXIS));
pnlAccDetails[0].add(lblWelcome); // adding label to form
lblMain.setText("<html>The following information that is collected will be used as part of the Example_App process to ensure that each user has unique Example_App paths. Please fill in all areas of the following tabs:</html>"); // main label that explains what happens, html used for formatting
pnlAccDetails[1].setLayout(new BorderLayout());
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_START);
pnlAccDetails[1].add(lblMain, BorderLayout.CENTER); //adding label to JFrame
pnlAccDetails[1].add(Box.createHorizontalStrut(20), BorderLayout.LINE_END);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(pnlAccDetails[0]);
add(pnlAccDetails[1]);
}
private JLabel lblWelcome;
private JLabel lblMain;
private JPanel[] pnlAccDetails;
}
I have tried using both a CardLayout and the "revalidate();" "repaint();" and "pack();" options and I'm stumped as to why it's not showing. Thanks in advance for any help that can be offered.
EDIT:
While cutting down my code, if the "resizing" method is removed, the objects are shown when the panels change. I would like to avoid having to remove this completely as it's a smooth transition for changing the JFrame size.
#John smith it is basic example of switch from one panel to other panel I hope this will help you to sort out your problem
Code:
package stack;
import java.awt.BorderLayout;
import java.awt.Dimension;
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;
public class RemoveAndAddPanel implements ActionListener{
JFrame frame;
JPanel firstPanel;
JPanel secondPanel;
JPanel controlPanel;
JButton nextButton;
public RemoveAndAddPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.add(new JLabel("FirstPanel"));
firstPanel.setPreferredSize(new Dimension(100,100));
secondPanel = new JPanel();
secondPanel.add(new JLabel("Second panel"));
secondPanel.setPreferredSize(new Dimension(100,100));
nextButton = new JButton("Next panel");
controlPanel = new JPanel();
nextButton.addActionListener(this);
controlPanel.add(nextButton);
frame.setLayout(new BorderLayout());
frame.add(firstPanel,BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.setSize(300,100);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == nextButton) {
frame.remove(firstPanel);
frame.add(secondPanel);
nextButton.setEnabled(false);
}
frame.validate();
}
public static void main(String args[]) {
new RemoveAndAddPanel();
}
}
As mentioned in the edit, the problem lay within the resizing method. When the timer stopped, it wouldn't go anywhere, causing the UI to not load. The fix to the code is clearing the screen and adding the call to resizing to the actionlistener. Then adding a call to the next method after:
timer.stop();
Thanks for getting me to remove the mess around it and find the source of the problem #matt & #Hovercraft Full of Eels upvotes for both of you.
The main thing to consider while changing panel in a jframe is the layout, for a body(main) panel to change to any other panel the parent panel must be of type CardLayout body.setLayout(new java.awt.CardLayout());
After that you can now easily switch between panels wiht the sample code below
private void updateViewLayout(final HomeUI UI, final JPanel paneeelee){
final JPanel body = UI.getBody(); //this is the JFrame body panel and must be of type cardLayout
System.out.println("Page Loader Changing View");
new SwingWorker<Object, Object>() {
#Override
protected Object doInBackground() throws Exception {
body.removeAll();//remove all visible panel before
body.add(paneeelee);
body.revalidate();
body.repaint();
return null;
}
#Override
protected void done() {
UI.getLoader().setVisible(false);
}
}.execute();
}
I am creating a battleship game with 4 classes using sockets. A computer, player message and a menu class. To start the game I run the computer class which is the server then I run the menu class which bring up the menu. Through the menu I click start to create a new player object which looks like this
public static void runPlayer()
{
Player client = new Player(); //creates player
client.createBoard();
client.run();
}
this runs perfectly runs without the menu class if i run the computer class then the player class, the game runs successfully. But when i call the run player method in the menu a window pops up with nothing in it.Here is my Menu class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import sun.audio.*;
public class Menu {
private javax.swing.JLabel image;
private static final int EXIT_ON_CLOSE = 0;
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JLabel statusbar = new JLabel(" Battleship");
JLabel Battleship = new JLabel(" Battleship ");
static AudioPlayer MGP = AudioPlayer.player;
static AudioStream BGM;
AudioData MD;
static ContinuousAudioDataStream loop = null;
public static void waiting (int n)
{
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < n);
}
public Menu()
{
frame.setTitle("Battleship");
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
Battleship.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
panel.setLayout(null);
JButton start = new JButton("Start");
start.setBounds(100, 660, 80, 25);
JButton exit = new JButton("Exit");
exit.setBounds(190, 660, 80, 25);
JButton StopMusic = new JButton("Stop Music");
StopMusic.setBounds(300, 660, 160, 25);
JButton StartMusic = new JButton("Start Music");
StartMusic.setBounds(470, 660, 160, 25);
Battleship.setFont(new Font("Courier New", Font.ITALIC, 36));
Battleship.setForeground(Color.BLACK);
image = new javax.swing.JLabel();
image.setIcon(new javax.swing.ImageIcon("./battleship2.jpg"));
frame.add(image, BorderLayout.EAST);
frame.pack();
frame.add(start);
frame.add(exit);
frame.add(StopMusic);
frame.add(StartMusic);
frame.add(panel);
frame.add(statusbar, BorderLayout.SOUTH);
frame.add(Battleship, BorderLayout.NORTH );
frame.setSize(700, 800);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
music();
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
frame.dispose(); //closes frame
stopMusic(); //stops music
//waiting(500);
runPlayer();
}}
});
StopMusic.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
stopMusic();
}
}
});
StartMusic.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
startMusic();
}
}
});
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println( "Ending Game" );
System.exit(0);
}
});}
public static void music()
{
try
{
InputStream test = new FileInputStream("./battle.wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop);
}
public void stopMusic()
{
if (BGM != null)
AudioPlayer.player.stop(BGM);
if (loop != null)
AudioPlayer.player.stop(loop);
}
public void startMusic() {
try
{
InputStream test = new FileInputStream("./battle.wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop);
}
public static void runPlayer()
{
Player client = new Player(); //creates player
client.createBoard();
client.run();
}
public static void main(String[] args)
{
new Menu();
}
}
I think my problem is somewhere in this listener method
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
frame.dispose(); //closes frame
stopMusic(); //stops music
//waiting(500);
runPlayer();
}}
});
It's a bit hard to answer this question with the information provided. But I'll have to guess what the runPlayer() method is doing. I'm assuming there's some type of while loop in there that prevents the Event Dispatch Thread from refreshing the new JFrame you created.
Try to place the stopMusic() and runPlayer() in a new thread.
Basically something like this
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose(); // closes frame
new Thread(){
public void run(){
stopMusic(); // stops music
runPlayer();
}
}.start();
}
});
I think the problem lies outside the code you've shown; it could be anything from a missing setVisible() to a synchronization problem. FWIW, I have a few observation about the code:
Build your GUI on the EDT, #David Young just suggested.
Use static constants to avoid repeating yourself.
Don't use spaces to format labels; use the JLabel alignment constants.
Instead of a null layout, use nested layouts to get the result you want.
To avoid calling a public method in the constructor, you've duplicated the code of startMusic(). Instead, invoke it after the constructor completes.
Here's an example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import sun.audio.*;
public class Menu {
private static final String TITLE = "Battleship";
private static final String SOUND_FILE = "./battle.wav";
private javax.swing.JLabel image;
JFrame frame = new JFrame(TITLE);
JPanel center = new JPanel(new BorderLayout());
JLabel statusbar = new JLabel(TITLE);
JLabel battleship = new JLabel(TITLE, JLabel.CENTER);
static AudioPlayer MGP = AudioPlayer.player;
static AudioStream BGM;
static ContinuousAudioDataStream loop = null;
AudioData MD;
public Menu() {
frame.setTitle("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
battleship.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
JButton start = new JButton("Start");
JButton exit = new JButton("Exit");
JButton StopMusic = new JButton("Stop Music");
JButton StartMusic = new JButton("Start Music");
battleship.setFont(new Font("Courier New", Font.ITALIC, 36));
battleship.setForeground(Color.BLACK);
image = new JLabel();
image.setHorizontalAlignment(JLabel.CENTER);
image.setIcon(new ImageIcon("./battleship2.jpg"));
center.add(image, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(start);
panel.add(exit);
panel.add(StopMusic);
panel.add(StartMusic);
center.add(panel, BorderLayout.SOUTH);
frame.add(battleship, BorderLayout.NORTH);
frame.add(center, BorderLayout.CENTER);
frame.add(statusbar, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//frame.dispose();
stopMusic();
runPlayer();
}
});
StopMusic.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stopMusic();
}
});
StartMusic.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startMusic();
}
});
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ending Game");
System.exit(0);
}
});
}
public void stopMusic() {
if (BGM != null) {
AudioPlayer.player.stop(BGM);
}
if (loop != null) {
AudioPlayer.player.stop(loop);
}
}
public void startMusic() {
try {
InputStream test = new FileInputStream(SOUND_FILE);
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
MGP.start(loop);
} catch (FileNotFoundException e) {
System.out.print(e.toString());
} catch (IOException error) {
System.out.print(error.toString());
}
}
public static void runPlayer() {
Player client = new Player();
client.createBoard();
client.run();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Menu menu = new Menu();
menu.startMusic();
}
});
}
// stub for missing class
private static class Player {
void createBoard() {}
void run() {}
}
}