Retrieving filename from Jfilechooser into JList - java

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

Related

Java JFrame why not display a picture?

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.

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

Add images in an array by selecting images from file chooser

In this program, I am trying to select images from users using filechooser and then displaying those images. By default I added 2 images. When I add more images it doesn't display?
Below is my entire code
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class CLayout {
JFrame frame = new JFrame("CardLayout demo");
JPanel panelCont = new JPanel();
LoginView log = new LoginView();
JPanel Img = new ImageGallery();
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
log.setLayout(new BoxLayout(log, BoxLayout.PAGE_AXIS));
Img.setLayout(new BoxLayout(Img, BoxLayout.PAGE_AXIS));
panelCont.add(log, "1");
panelCont.add(Img, "2");
cl.show(panelCont, "1");
ActionListener loginListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userName = log.getUserName();
char[] password = log.getPassword();
String pass=new String(password);
if (LoginView.LOGIN.equals(e.getActionCommand())) {
if(userName.equals("imagegallery")&& pass.equals("12345"))
cl.show(panelCont, "2");
}
}
};
log.addActionListener(loginListener);
frame.add(panelCont);
frame.setSize(800,600);
frame.setTitle(" Image Gallery ");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
class ImageGallery extends JPanel {
private ImageIcon myImage1 = new ImageIcon ("Chrysanthemum.jpg");
private ImageIcon myImage2 = new ImageIcon ("Desert.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages =new ImageIcon[10];
private int curImageIndex=0;
private int count=0;
private int total=1;
public ImageGallery () {
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
add(ImageGallery, BorderLayout.CENTER);
JButton PREVIOUS = new JButton ("Previous");
JButton NEXT = new JButton ("Next");
JDialog.setDefaultLookAndFeelDecorated(true);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName().toString());
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
System.out.println(myImages.length);
int n=2+count;
myImages[n]=tImage;
total=total+count+1;
count++;
System.out.println(total+" "+count);
}
}
});
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,3));
add(Menu, BorderLayout.NORTH);
Menu.add(PREVIOUS);
Menu.add(NEXT);
Menu.add(button);
//register listener
PreviousButtonListener PreviousButton = new PreviousButtonListener ();
NextButtonListener NextButton = new NextButtonListener ();
//add listeners to corresponding componenets
PREVIOUS.addActionListener(PreviousButton);
NEXT.addActionListener(NextButton);
}
class PreviousButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>0 && curImageIndex <=total) {
ImageGallery.remove(0);
curImageIndex=curImageIndex-1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage1));
curImageIndex=0;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
class NextButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>=0 && curImageIndex <total){
ImageGallery.remove(0);
curImageIndex = curImageIndex + 1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImages[total]));
curImageIndex=total ;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
}
class LoginView extends JPanel {
JLabel userLabel = new JLabel("User");
JTextField userText = new JTextField(20);
JLabel passwordLabel = new JLabel("Password");
JPasswordField passwordText = new JPasswordField(20);
private final JButton loginButton;
private final JButton registerButton;
public static final String LOGIN = "Login";
public static final String REGISTER = "Regster";
public LoginView() {
setLayout(new GridLayout(0, 2));
userLabel.setBounds(10, 10, 80, 25);
add(userLabel);
userText.setBounds(10, 10, 60, 25);
add(userText);
passwordLabel.setBounds(10, 40, 80, 25);
add(passwordLabel);
passwordText.setBounds(100, 40, 160, 25);
add(passwordText);
loginButton = new JButton("login");
loginButton.setActionCommand(LOGIN);
registerButton = new JButton("register");
registerButton.setActionCommand(REGISTER);
add(loginButton);
}
public void addActionListener(ActionListener listener) {
loginButton.addActionListener(listener);
registerButton.addActionListener(listener);
}
public String getUserName() {
return userText.getText();
}
public char[] getPassword() {
return passwordText.getPassword();
}
}
Problem is in this line
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
you need to remove double-quotes in order to read actual file name.
ImageIcon tImage=new ImageIcon(selectedFile.getName().toString());
Hope this helps.

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

Categories

Resources