Java JFrame why not display a picture? - java

In the createWorkPanel() method I created a Label and put a picture there, but the picture is not displayed on the screen. Maybe someone knows why, please tell me?
Here is my code:
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class MainWindow extends JFrame {
private JButton button1;
public MainWindow() throws IOException
{
setLayout(new BorderLayout());
createWorkPanel();
setTitle("Графический дизайнер");
//setDefaultLookAndFeelDecorated(true);
setSize(1000,600);
// setLocation(400,100);
// setVisible(true);
// pack(); // automatically size the window to fit its components
setLocationRelativeTo(null); // center this window on the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void createWorkPanel() throws IOException
{
setLayout(new FlowLayout());
button1 = new JButton("Load Images");
button1.setActionCommand("Button 1 was prassed!");
add(button1);
ActionListener actionListener = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File fImg = MyFileChooser.chooseFile("Image Files (png & jpg)", "png", "jpg");
if (fImg != null)
{
JLabel background=new JLabel(new ImageIcon(fImg.getAbsolutePath()));
// background.setLayout(new FlowLayout());
add(background);
System.out.println(" файл создан");
}
}
};
button1.addActionListener(actionListener);
}
public static void main (String [] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new MainWindow ().setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
class MyFileChooser {
public static File chooseFile(String description, String... extensions) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + selectedFile.getAbsolutePath());
return selectedFile;
} else {
return null;
}
}
}

Follow the below code.
if (fImg != null) {
JLabel background = new JLabel(new ImageIcon(fImg.getAbsolutePath()));
add(background);
MainWindow.this.revalidate();
}
Adding MainWindow.this.revalidate(); should help.

Related

Retrieving filename from Jfilechooser into JList

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

JList gets updated but just allow users to select items once

I have a JList that is located in a JScrollPane. The application has a button for users to browse fileSystem and select a category to show its files and folders.
First time user clicks on the button JList shows the list and enables user to select from the list but if user clicks on the browse button for the second time new items will be shown but
he wont be able to select any item from the list anymore.
public class Main {
private JFrame frame;
final JFileChooser fc = new JFileChooser();
private JScrollPane scrollPane;
File directory;
JList<File> list;
private final Action action_1 = new SwingAction_1();
private final Action action_2 = new SwingAction_2();
JTextArea message;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list = new JList<File>();
JButton btnBut1 = new JButton("Convert1");
btnBut1.setBounds(401, 6, 114, 29);
btnBut1.setAction(action_1);
JButton btnBut2 = new JButton("Convert2");
btnBut2.setBounds(523, 6, 117, 29);
btnBut2.setAction(action_2);
JButton btnChooseDirectory = new JButton("Choose Directory");
btnChooseDirectory.setBounds(59, 6, 153, 29);
btnChooseDirectory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
directory = fc.getSelectedFile();
File[] filesInDir = directory.getAbsoluteFile().listFiles();
addFilesToList(filesInDir);
}
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnChooseDirectory);
JLabel lblFilesMsg = new JLabel("List of files in the directory:");
lblFilesMsg.setBounds(6, 64, 175, 16);
frame.getContentPane().add(lblFilesMsg);
frame.getContentPane().add(btnBut1);
frame.getContentPane().add(btnBut2);
message = new JTextArea();
message.setBounds(6, 426, 788, 146);
message.setEditable(false);
message.setLineWrap(true);
frame.getContentPane().add(message);
frame.setTitle(APP_NAME);
}
private void addFilesToList(File[] filesInDir) {
list.setListData(filesInDir);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
scrollPane = new JScrollPane(list);
scrollPane.setBounds(6, 81, 788, 330);
scrollPane.setBackground(Color.WHITE);
frame.getContentPane().add(scrollPane);
scrollPane.revalidate();
}
private class SwingAction_1 extends AbstractAction {
public SwingAction_1() {
putValue(NAME, "Converter1");
}
public void actionPerformed(ActionEvent e) {
MyAction1 act = new MyAction1();
act.method1(list.getSelectedValuesList());
}
}
private class SwingAction_2 extends AbstractAction {
public SwingAction_2() {
putValue(NAME, "Converter2");
}
public void actionPerformed(ActionEvent e) {
MyAction2 act = new MyAction2();
act.method2(list.getSelectedValuesList());
}
}
}
I would suggest your problem(s) start with:
Creating a JScrollPane within the addFilesToList method: scrollPane = new JScrollPane(list);. Create the JList AND JScrollPane ONCE, there should be no need to continuously recreate these
Use of null layouts. This has been suggested to you more times then I care to remember. Seriously, make the time to learn the layout managers, it will solve so many small and annoying problems
The problem here...
scrollPane.setBounds(6, 81, 788, 330);
scrollPane.setBackground(Color.WHITE);
frame.getContentPane().add(scrollPane);
Is, which JScrollPane is actually visible on the screen? Which one actually contains the JList? You have more than one now...
And yet, another, simple, runnable 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.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JFileChooser fc;
private JList<File> listOfFiles;
private JLabel selectedFile;
public TestPane() {
setLayout(new BorderLayout());
JButton browse = new JButton("Browse");
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (fc == null) {
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File directory = fc.getSelectedFile();
File[] filesInDir = directory.getAbsoluteFile().listFiles();
addFilesToList(filesInDir);
}
}
protected void addFilesToList(File[] filesInDir) {
DefaultListModel<File> model = (DefaultListModel<File>) listOfFiles.getModel();
model.removeAllElements();
for (File file : filesInDir) {
model.addElement(file);
}
}
});
add(browse, BorderLayout.NORTH);
listOfFiles = new JList<>(new DefaultListModel<File>());
listOfFiles.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
File file = listOfFiles.getSelectedValue();
selectedFile.setText("You selected: " + (file == null ? "Nothing" : file.getPath()));
}
}
});
add(new JScrollPane(listOfFiles));
selectedFile = new JLabel("You selected: Nothing");
add(selectedFile, BorderLayout.SOUTH);
}
}
}

Java adding Menu to Frame

I am trying to write a clipboard program that can copy/paste and save to a txt file.
While the program works, I am trying to change the buttons into a Menu with MenuItems,
however, I cannot figure out how to use the Menu item properly, as I cannot add it to a panel.
Please notice I am using AWT and not Swing, so no JPanel/JFrame, etc.
Any tip/help is appreciated.
This is my code and attempt at changing it into a menu, please let me know what I am doing wrong:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CheesyWP extends Frame implements ActionListener {
/**
* #param args
*/
//new panel for menu
Panel north;
//original
Panel center;
Panel south;
Button save;
Button load;
Button clip;
Button finish;
Menu mn;
MenuItem mSave;
MenuItem mLoad;
MenuItem mClip;
MenuItem mFinish;
TextArea ta;
public static void main(String[] args) {
// TODO Auto-generated method stub
CheesyWP cwp = new CheesyWP();
cwp.doIt();
}
public void doIt() {
center = new Panel();
south = new Panel();
clip = new Button("Open Clipboard");
save = new Button("Save");
load = new Button("Load");
finish = new Button("Finish");
//menu items
north = new Panel();
mn = new Menu();
mSave = new MenuItem("Save");
mLoad = new MenuItem("Load");
mClip = new MenuItem("Open Clipboard");
mFinish = new MenuItem("Finish");
mn.add(mSave);
mn.add(mLoad);
mn.add(mClip);
mn.add(mFinish);
mSave.addActionListener(this);
mLoad.addActionListener(this);
mClip.addActionListener(this);
mFinish.addActionListener(this);
//north.add(mn); <-------//PROBLEM HERE
clip.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
finish.addActionListener(this);
ta = new TextArea(20, 80);
center.add(ta);
south.add(load);
south.add(save);
south.add(clip);
south.add(finish);
this.add(center, BorderLayout.CENTER);
this.add(south, BorderLayout.SOUTH);
this.setSize(600, 300);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == save) {
try {
File junk = new File("junk.txt");
FileWriter fw = new FileWriter(junk);
fw.write(ta.getText()); // write whole TextArea contents
fw.close();
} catch (IOException ioe) {
}
}// ends if
if (ae.getSource() == load) {
String temp = "";
try {
File junk = new File("junk.txt");
FileReader fr = new FileReader(junk);
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
ta.append(temp + "\n");
}
br.close();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
if (ae.getSource() == finish) {
System.exit(0);
}
if(ae.getSource()==clip){
new ClipBoard();
}
}
class ClipBoard extends Frame {
public ClipBoard() { // a constructor
this.setTitle("Clipboard");
this.setLayout(new FlowLayout());
this.add(new TextArea(10, 50));
this.setSize(400, 160);
this.setVisible(true);
}
}
}
I hope this code help you:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JMenuTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JMenuTest() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu connectionMenu = new JMenu("Connection");
menuBar.add(connectionMenu);
JMenuItem menuItemConnect = new JMenuItem("Connect");
menuItemConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Connected");
}
});
connectionMenu.add(menuItemConnect);
JMenuItem menuItemDisconnect = new JMenuItem("Disconnect");
menuItemDisconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Disconnected");
}
});
connectionMenu.add(menuItemDisconnect);
JMenuItem menuItemExit = new JMenuItem("Exit");
menuItemExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
connectionMenu.add(menuItemExit);
JMenu mnNewMenu_1 = new JMenu("New menu");
menuBar.add(mnNewMenu_1);
this.setVisible(true);
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* #param args
*/
public static void main(String[] args) {
new JMenuTest();
}
}

Not able to switch cards in cardlayout in single jframe

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);
}
}
}
}

Battleship Application crashes if I run it through the main menu after slicking on start

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() {}
}
}

Categories

Resources