Java Menu AWT into Panel - java

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

Just change this
Panel north;
To this
MenuBar north;
Because using awt library , you cannot add Menu to Panel , however you can add Menu to MenuBar

this.validate();
Swing components have a default state of being invalid and won't be painted to the screen unless validated (by calling the .validate() method on either the component itself or on one of the parent containers).

Related

How would I fill my TextFields after I select an item from JList

i'm having some trouble with a homework problem, and still trying to wrap my head around GUI logically. I have created all my text fields (contactType, name, address, city, state, etc...) and have created an actionListener to populate my JList with names when I click open from the JMenu. I'm running into trouble filling in the appropriate text fields when I select the name from the list. I tried to just print out to console to see if it would print out at least the name, but that's not even working. Any help would be great, thanks.
Here's some of my code so far:
public class AddressBookGUI extends JFrame
{
private final int WIDTH = 450;
private final int HEIGHT = 300;
private JLabel currentlySelected;
private JTextField contactTypeTextField;
private JTextField nameTextField;
private JTextField streetAddressTextField;
private JTextField cityTextField;
private JTextField stateTextField;
private JTextField zipTextField;
private JTextField phoneTextField;
private JTextField emailTextField;
private JTextField photoTextField;
private JList nameList ;
private DefaultListModel model;
private JTextArea statusTextArea;
private AddressBook addressBook;
private JButton addButton;
private JButton editButton;
private JButton sortByZipButton;
private JMenuItem addItem;
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem exitItem;
private JMenuItem editContactItem;
private JMenuItem aboutItem;
private JMenuItem deleteItem;
private JComboBox<String> jComboStates;
private JComboBox <Enum> jComboContactType;
private String [] readStates()
{
ArrayList<String> array = new ArrayList<>();
try
{
FileInputStream fStream = new FileInputStream ("States.txt");
BufferedReader buffer = new BufferedReader (new InputStreamReader (fStream));
String strLine;
while ((strLine = buffer.readLine()) != null)
{
String line = buffer.readLine();
String [] state = line.split ("\n");
array.add(strLine);
}
buffer.close();
}
catch (Exception e)
{
}
return array.toArray(new String[array.size()]);
}
private ArrayList<String> readContacts()
{
File cFile = new File ("Contacts.txt");
BufferedReader buffer = null;
ArrayList <String> contact = new ArrayList<String>();
try
{
buffer = new BufferedReader (new FileReader (cFile));
String text;
String sep;
while ((sep = buffer.readLine()) != null)
{
String [] name = sep.split (",");
text = name[1];
contact.add(text);
}
}
catch (FileNotFoundException e)
{
System.out.print ("error");
}
catch (IOException k)
{
System.out.print ("error);
}
return contact;
}
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu ("File");
openItem = new JMenuItem ("Open...");
fileMenu.add (openItem);
fileMenu.addSeparator();
saveItem = new JMenuItem ("Save...");
fileMenu.add (saveItem);
fileMenu.addSeparator();
exitItem = new JMenuItem ("Exit");
fileMenu.add (exitItem);
JMenu editMenu = new JMenu ("Edit");
editContactItem = new JMenuItem ("Edit Contact");
editMenu.add (editContactItem);
addItem = new JMenuItem ("Add Contact");
editMenu.add (addItem);
deleteItem = new JMenuItem ("Delete Contact");
editMenu.add (deleteItem);
JMenu helpMenu = new JMenu ("Help");
aboutItem = new JMenuItem ("About");
helpMenu.add(aboutItem);
menuBar.add (fileMenu);
menuBar.add (editMenu);
menuBar.add (helpMenu);
setJMenuBar (menuBar);
//code that creates new text fields for all attributes
//code that sets textfields to uneditable
JPanel topPanel = new JPanel()
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add (currentlySelected, BorderLayout.CENTER);
leftPanel.add (new JScrollPane(), BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JPanel infoPanel = new JPanel (new BorderLayout());
GridLayout layout = new GridLayout (9,1);
JPanel labelsPanel = new JPanel (layout);
JPanel valuesPanel = new JPanel (layout);
// code that added lables and values to panel
infoPanel.add (labelsPanel, BorderLayout.WEST);
infoPanel.add (valuesPanel, BorderLayout.CENTER);
centerPanel.add (infoPanel);
setLayout (new BorderLayout());
add (topPanel, BorderLayout.NORTH);
add (leftPanel, BorderLayout.WEST);
add (centerPanel, BorderLayout.CENTER);
addressBook = new AddressBook();
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
}
});
editContactItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
nameTextField.setEditable (true);
streetAddressTextField.setEditable (true);
cityTextField.setEditable (true);
jComboStates.setEditable (true);
zipTextField.setEditable (true);
phoneTextField.setEditable (true);
emailTextField.setEditable (true);
photoTextField.setEditable (true);
}
});
saveItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
addressBook.Save ( );
}
});
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
};
nameList.addMouseListener(mouseListener);
}
I tried cut out some of the tedious code to keep it short. If I could get a skeleton or a nudge in the right direction, it would be a great help.
So i've changed it up a bit, once I select open, it populates the JList with the names, then when I double click on a name it only fills the nameTextField, addressTextField, and cityTextField all with the name of the contact I selected
ex) Name: Zoidberg, Address: Zoidberg, City: Zoidberg
here's my code:
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
if (nameList.getModel().getElementAt(index) != null && nameList.getModel().getElementAt(index) instanceof String)
{
nameTextField.setText((String) nameList.getModel().getElementAt (index));
streetAddressTextField.setText((String) nameList.getModel().getElementAt (index));
cityTextField.setText((String) nameList.getModel().getElementAt (index));
stateTextField.setText((String) nameList.getModel().getElementAt (index));
zipTextField.setText((String) nameList.getModel().getElementAt (index));
phoneTextField.setText((String) nameList.getModel().getElementAt (index));
emailTextField.setText((String) nameList.getModel().getElementAt (index));
photoTextField.setText((String) nameList.getModel().getElementAt (index));
}
}
}
};
nameList.addMouseListener(mouseListener);
nameList = new JList (model);
You add data to the JList with the above code.
But then later you do:
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
Which creates an empty List and adds a ListSelectionListener to this list. This serves no purpose since the JList is empty and is not visible on the GUI anyway.
Add the ListSelectListener to the JList when you create the JList and add data to it:
nameList = new JList (model);
nameList.addListSelectionListener(...);
I second all that Rob Camick writes. Also, you're only adding name Strings to your list and not complete Address objects, and so key information is lost. To gain it, make your JList a list of Address objects, give it a custom cell renderer that shows only the name, but this will allow your selected object to have all the data that you need.

Java: NullPointerException thrown when JButton is clicked in the Flash Card Game

Details: It's a Flash Card game, each Card has question and answer.
QuizCard is the class of Cards having functions like getQuestion(), getAnswer(), setQuestion(), setAnswer() and two String Instances as question and answer. A parameterised constructor takes two strings, first as question and second as answer.
I saved questions and answers in a text file, where question and answer is separated by a "/". All new questions start from a new line.
E.g. -> What is the Capital of India?/New Delhi
Where is the Taj Mahal?/Agra
Rest of the code can be easily understood.
Problem: When the "nextButton" is clicked it throws a NullPointerException and doesn't change the text on the "nextButton".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class QuizCardPlayer
{
private JFrame frame;
private JTextArea display;
private boolean isAnswer = true;
private JButton nextButton;
private ArrayList<QuizCard> cardList;
private int currentCardIndex;
public static void main(String[] args)
{
QuizCardPlayer player = new QuizCardPlayer();
player.go();
}
public void go()
{
frame = new JFrame("Quiz Card Player");
display = new JTextArea(6,20);
JPanel mainPanel = new JPanel();
Font bigFont = new Font("serif", Font.BOLD, 24);
display.setFont(bigFont);
JScrollPane scroller = new JScrollPane(display);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
display.setText("Lets Start!");
JButton nextButton = new JButton("Show Question");
mainPanel.add(scroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextButtonListener());
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem loadMenuItem = new JMenuItem("Load card set");
loadMenuItem.addActionListener(new LoadMenuListener());
fileMenu.add(loadMenuItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setVisible(true);
frame.setSize(300,300);
}
public class NextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.print("Called!!");
if(isAnswer)
{
nextButton.setText("Show Answer");
if( currentCardIndex < cardList.size() )
{
display.setText(cardList.get(currentCardIndex).getQuestion());
isAnswer = false;
}
else
{
display.setText("That was last Card.");
nextButton.setEnabled(false);
}
}
else
{
nextButton.setText("Next Card");
display.setText(cardList.get(currentCardIndex).getAnswer());
isAnswer = true;
currentCardIndex++;
}
}
}
public class LoadMenuListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
loadFile(openFile.getSelectedFile());
}
}
public void loadFile(File loadFile)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(loadFile));
String line="";
cardList = new ArrayList<QuizCard>();
while( (line = reader.readLine()) != null )
{
String[] result = line.split("/");
QuizCard card = new QuizCard(result[0] , result[1]);
cardList.add(card);
currentCardIndex=0;
}
reader.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
I am novice in Java having a experience of just one month, any suggestion is most welcome.
You are creating nextButton as an instance variable of class QuizCardPlayer, but inside go() method, you initializing the local variable nextButton and adding Listener to this local copy, and adding this local copy of nextButton to the mainPanel (which is visible on the VIEW ).
Though the instance variable remains null, as you never did assigned it to anythingy, and you trying to access this null variable inside NextButtonListener class, as follows:
nextButton.setText("Show Answer");
EDIT 1:
Simply replace this line inside go () method:
JButton nextButton = new JButton("Show Question");
to
nextButton = new JButton("Show Question");
This will work :-)

JList doesn't show on JScrollPane

I'm trying to open a text file using JFilechooser and put strings in JList. I think all the strings go into the list but I don't know why the strings don't appear on JScrollPane. Is there any problem with grouplayout? i don't know what to change..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.List;
public class WordFinder extends JFrame implements ActionListener {
private WordList words = new WordList();
private JScrollPane scroll;
private JLabel label;
private JLabel word;
private JTextField textArea;
private JButton button;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem, menuItem2;
private JFileChooser fc;
private JList list;
static private final String newline = "\n";
private int lineCount;
public WordFinder() {
super("Word Finder");
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
menuItem = new JMenuItem("Open...");
menuItem.addActionListener(this);
menuItem2 = new JMenuItem("Exit");
menuItem2.addActionListener(this);
menu.add(menuItem);
menu.add(menuItem2);
setJMenuBar(menuBar);
label = new JLabel("Find: ");
word = new JLabel(lineCount + " words total");
textArea = new JTextField();
textArea.setEditable(true);
textArea.setPreferredSize(new Dimension(200, 20));
button = new JButton("Clear");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText("");
}
});
scroll = makeListView();
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(200, 230));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(label)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(textArea)
.addComponent(word)
.addComponent(scroll))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(button)));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label)
.addComponent(textArea)
.addComponent(button))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(word))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(scroll));
setVisible(true);
pack();
// call System.exit() when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JScrollPane makeListView() {
// String[] labels = {"1", "2", "3"};
// list = new JList(labels);
JScrollPane listScroller = new JScrollPane(list);
return listScroller;
}
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
public void actionPerformed(ActionEvent e) {
DefaultListModel listModel = new DefaultListModel();
if (e.getSource() == menuItem) {
int returnVal = fc.showOpenDialog(WordFinder.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileName = file.getAbsolutePath();
try {
FileReader files = new FileReader(fileName);
BufferedReader br = new BufferedReader(files);
String str;
while((str = br.readLine()) != null) {
listModel.addElement(str);
//System.out.println(str);
lineCount++;
}
System.out.println(lineCount);
updateListView(listModel);
br.close();
} catch (Exception ex) {
ex.printStackTrace(System.out);
System.out.println("can't read file");
}
System.out.println("Opening: " + file.getName() + newline);
}
} else if (e.getSource() == menuItem2) {
setVisible(false);
dispose();
}
}
/**
* Main method. Makes and displays a WordFinder window.
* #param args Command-line arguments. Ignored.
*/
public static void main(String[] args) {
// In general, Swing objects should only be accessed from
// the event-handling thread -- not from the main thread
// or other threads you create yourself. SwingUtilities.invokeLater()
// is a standard idiom for switching to the event-handling thread.
SwingUtilities.invokeLater(new Runnable() {
public void run () {
// Make and display the WordFinder window.
new WordFinder();
}
});
}
}
When you call makeListView the JList is null as it hasn't been initialized yet...thus, you are basically saying scroll = new JScrollPane(null);...which isn't particularly helpful...
Next, when you call updateListView, you create a new instance of the JList and JScrollPane and do nothing with them...
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
so they will never be displayed on the screen...
To rectify this, you will need to make some modifications...
Create an instance of the JList and assign it to the instance field list, before you create the JScrollPane
Instead of creating new instances of the list and scroll, simply use JList#setModel
You may also like to have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
With JList, you affect the size of the JScrollPane through the use of JList#setVisibleRowCount and JList#setPrototypeCellValue

Create a JTextArea in a JPanel using Swing

I want to create a Jtextarea in the first half of the below panel under tab2. I want to iterate and write the contents present in the test.txt file into this newly created Jtext area. The text.txt file is present in the location (C:\test.txt). Can someone suggest me how to achieve this for the below code.(Note: The below code is a JPane with three tabs tab1,tab2,tab3) and the tab 2 has been splited into two halves.)
I am new to the Jtextarea concept so it will be nice from understanding viewpoint if anyone can provide some suggestion code for my below code:
text.txt contents in my local disk is as below
username:test1
Password:test1
DataBasename: testDB
CODE:
import javax.swing.*;
import java.awt.*;
public class SplitPaneExp {
public static void main(String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("WELCOME");
// A better close operation..
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
// this GridLayout will create a single row of components,
// with equal space for each component
JPanel tab2Panel = new JPanel(new GridLayout(0,1));
button = new JButton("2");
tab2Panel.add(button);
tab2Panel.add(new JButton("Second window"));
// add the panel containing two buttons to the tab
tab.add("tab2", tab2Panel);
button = new JButton("3");
tab.add("tab3", button);
// a better sizing method..
//frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class SplitPaneExp {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("WELCOME");
// A better close operation..
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
// this GridLayout will create a single row of components,
// with equal space for each component
JPanel tab2Panel = new JPanel(new GridLayout(0, 1));
// button = new JButton("2");
//Hi, I added a few things here!
String output = "";
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\test.txt")));
String line = br.readLine();
while(line != null) {
if(output.length() > 0) {
output = output + "\n";
}
output = output + line;
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
JTextArea jta = new JTextArea(output);
tab2Panel.add(jta);
// Done.
// tab2Panel.add(button);
tab2Panel.add(new JButton("Second window"));
// add the panel containing two buttons to the tab
tab.add("tab2", tab2Panel);
button = new JButton("3");
tab.add("tab3", button);
// a better sizing method..
//frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Hope it helps.

I am trying to use JFileChooser to view and display a file, unable to figure out how to display file

I am trying to open and view a file using JFileChooser, but am having issues viewing the file. Any help or critique is open, thanks mates.
package jmenu_bar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
/**
*
* #author Stafford J Villavicencio
*/
public class Jmenu_Bar extends JFrame
{
public static void main(String[] args)
{
//create JFrame
final JFrame frame = new JFrame();
frame.setTitle(" JMenuBar Practice ");
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//create JMenuBar
JMenuBar jbar = new JMenuBar();
jbar.setBorder(new BevelBorder(BevelBorder.RAISED));
//add JMenuBar to JFrame
frame.setJMenuBar(jbar);
//create JMenu File
JMenu file = new JMenu(" File");
//add seperator between sub-Options
file.addSeparator();
//add JMenu file to JMenuBAr
jbar.add(file);
//create JMenuItem exit
JMenuItem exit = new JMenuItem(" Exit");
//create ActionListener for exit
exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
//add exit to file menu
file.add(exit);
/*IM trying to have JMenuItem "open" actualy open and display selected file within the JFrame......>
*create JMenuItem open
*/
JMenuItem open = new JMenuItem(" Open");
//create actionListener for open
open.addActionListener(new ActionListener()
{
JFileChooser fChoose = new JFileChooser();
#Override
public void actionPerformed(ActionEvent e)
{
fChoose.showOpenDialog(frame);
}
});
file.add(open);
//create JMenu edit
JMenu edit = new JMenu(" Edit");
jbar.add(edit);
//create JMenuItem save
JMenuItem save = new JMenuItem(" Save");
edit.add(save);
}
}
All the file choose does is give you the name of a file to read. You are still responsible for reading the text of the file and loading it into a Swing component.
I would suggest using a JTextArea to display a text file. Then you can just use the read(...) method.
First you should read the Swing tutorial on How to Use A File Chooser. Then once you get the file name you can do something like:
FileReader reader = new FileReader( the file name );
BufferedReader br = new BufferedReader( reader );
textArea.read(br, null);
Code is untested, I'll let you work out the details.
i looked at your program, it shows nothing to me...you just messed up, lets take a look at my code of JFile Chooser.. this code is just an example, this code opens the .gif, .jpg file, means it works as a image viewer,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageViewer extends JFrame
{
static JFileChooser imageChooser = new JFileChooser();
static JLabel imageLabel = new JLabel();
public static void main(String args[])
{
//construct frame
new ImageViewer().show();
}
public ImageViewer()
{
// create frame
setTitle("Image Viewer");
setResizable(false);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
String[] ext = new String[] {"gif", "jpg"};
gridConstraints.gridy = 0;
getContentPane().add(imageChooser, gridConstraints);
imageChooser.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
imageChooserActionPerformed(e);
}
});
imageLabel.setPreferredSize(new Dimension(270, 300));
imageLabel.setBorder(BorderFactory.createLineBorder(Color.RED)); imageLabel.setOpaque(true);
imageLabel.setBackground(Color.white);
imageLabel.setHorizontalAlignment(SwingConstants.CENTER);
imageLabel.setVerticalAlignment(SwingConstants.CENTER);
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(imageLabel, gridConstraints);
pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * (screenSize.height - getHeight())), getWidth(), getHeight());
}
private void imageChooserActionPerformed(ActionEvent e)
{
// create and display graphic if open selected
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION))
{
ImageIcon myImage = new ImageIcon(imageChooser.getSelectedFile().toString());
imageLabel.setIcon(myImage);
}
}
private void exitForm(WindowEvent e)
{
System.exit(0);
}
}
I think you're saying that you don't know how to see which file the user has selected.
final JFileChooser jfc = new JFileChooser();
int returnVal = jfc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selected = jfc.getSelectedFile();
//do something with the file
}
}
use int returnVal = jfc.showOpenDialog(this); to launch the open dialog. This way, when the user clicks a button (either cancel or approve(open)), it will return an int value. So, the if statement says: If the button clicked was "open", then get the file they chose, call it selected and do something with it.
Let me know if I need to walk you through anything in more depth.

Categories