Loading a textfile into a JtextArea - java

I've been trying for hours to trying to load the contents of a text file into a JTextArea. I'm able to load the text into the console but not into the JTextArea I don't know what I'm doing wrong. Any help is appreciated thanks!
The class for the program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class LoadClass extends JPanel
{
JPanel cards;
private JPanel card1;
private JTextArea textarea1;
private int currentCard = 1;
private JFileChooser fc;
public LoadClass()
{
Font mono = new Font("Monospaced", Font.PLAIN, 12);
textarea1 = new JTextArea();
textarea1.setFont(mono);
card1 = new JPanel();
card1.add(textarea1);
cards = new JPanel(new CardLayout());
cards.add(card1, "1");
add(cards, BorderLayout.CENTER);
setBorder(BorderFactory.createTitledBorder("Animation here"));
setFont(mono);
}
public void Open()
{
textarea1 = new JTextArea();
JFileChooser chooser = new JFileChooser();
int actionDialog = chooser.showOpenDialog(this);
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File( chooser.getSelectedFile( ) + "" );
if(fileName == null)
return;
if(fileName.exists())
{
actionDialog = JOptionPane.showConfirmDialog(this,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION)
return;
}
try
{
String strLine;
File f = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(f));
while((strLine = br.readLine()) != null)
{
textarea1.append(strLine + "\n");
System.out.println(strLine);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
}
The Main Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LoadMain extends JFrame
{
private LoadClass canvas;
private JPanel buttonPanel;
private JButton btnOne;
public LoadMain()
{
super("Ascii Art Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
canvas = new LoadClass();
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
add(canvas, BorderLayout.CENTER);
pack();
setSize(800, 800);
setVisible(true);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
btnOne = new JButton("Load");
buttonPanel.add(btnOne);
btnOne.addActionListener(new btnOneListener());
}
private class btnOneListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btnOne)
{
canvas.Open();
}
}
}
public static void main(String[] args)
{
new LoadMain();
}
}

public void Open()
{
textarea1 = new JTextArea();
Change that to:
public void Open()
{
//textarea1 = new JTextArea(); // or remove completely
The second field created is confusing things.

Related

Resize JOptionPane Dialog and lines in a dialogs

My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}

Trying to load a .txt file into JFrame (JFileChooser)

So I'm in college trying to do a JFrame assignment and I'm trying to be able to load a .txt file through JFileChooser and have the text inside the file to show up in the few JTextFields that are inside this JFrame. Right now it's not working and with all the information I have from my class lectures and such, I can't find a way around this problem.
So here's the full code, the specific section I'm trying to work with is the case: "Load" section.
package assignment3;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class SocialMediaList extends JFrame {
private JPanel display;
private JLabel siteNameLabel;
private JTextField siteName;
private JLabel userIDLabel;
private JTextField userID;
private JLabel contactsLabel;
private JTextField contacts;
private JPanel btns;
private JButton loadBtn;
private JButton addBtn;
private JButton saveBtn;
private JButton exitBtn;
private JPanel list;
private JList myList;
private ArrayList<SocialMedia> mediaList;
public SocialMediaList() {
mediaList = new ArrayList();
myList = new JList(mediaList.toArray());
this.setLayout(new GridLayout(2,1,5,5));
display = new JPanel();
display.setLayout(new GridLayout(5,2,5,5));
siteNameLabel = new JLabel(" Site Name: ");
siteName = new JTextField(10);
userIDLabel = new JLabel(" User ID: ");
userID = new JTextField(10);
contactsLabel = new JLabel(" No. of Contacts: ");
contacts = new JTextField(10);
display.add(siteNameLabel);
display.add(siteName);
display.add(userIDLabel);
display.add(userID);
display.add(contactsLabel);
display.add(contacts);
this.add(display);
btns = new JPanel();
btns.setLayout(new GridLayout(1,3,5,5));
loadBtn = new JButton("Load");
loadBtn.setActionCommand("Load");
addBtn = new JButton("Add");
saveBtn = new JButton("Save");
exitBtn = new JButton("Exit");
btns.add(loadBtn);
btns.add(addBtn);
btns.add(saveBtn);
btns.add(exitBtn);
this.add(btns);
list = new JPanel();
list.setLayout(new FlowLayout());
JScrollPane myScrollPane = new JScrollPane(myList);
list.add(myScrollPane);
setLayout(new BorderLayout());
this.add(display,BorderLayout.NORTH);
this.add(btns,BorderLayout.CENTER);
this.add(list,BorderLayout.SOUTH);
ButtonListeners buttonListener = new ButtonListeners();
loadBtn.addActionListener(buttonListener);
addBtn.addActionListener(buttonListener);
saveBtn.addActionListener(buttonListener);
exitBtn.addActionListener(buttonListener);
}
public static void main(String[] args) {
SocialMediaList list = new SocialMediaList();
list.setTitle("Assignment #3");
list.setSize(600,350);
list.setLocationRelativeTo(null);
list.setVisible(true);
list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ButtonListeners implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()) {
case "Load":
File file;
try {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
SocialMedia account = mediaList.get(myList.getSelectedIndex());
siteName.setText(account.getSiteName());
userID.setText(account.getUserID());
contacts.setText(String.valueOf(account.getContacts()));
myList.setListData(mediaList.toArray());
add(siteName);
add(userID);
add(contacts);
if (mediaList.size() > 0) {
myList.setSelectedIndex(0);
}
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(SocialMediaList.class.getName()).log(Level.SEVERE, null, ex);
}
case "Add":
String s = siteName.getText();
String u = userID.getText();
int c = Integer.valueOf(contacts.getText());
SocialMedia mySocialMedia = new SocialMedia();
mySocialMedia.setSiteName(s);
mySocialMedia.setUserID(u);
mySocialMedia.setContacts(c);
mediaList.add(mySocialMedia);
myList.setListData(mediaList.toArray());
break;
case "Save":
try {
FileWriter writer = new FileWriter("socialMedia2.txt");
writer.write(mediaList.toString());
writer.write(myList.toString());
writer.close();
} catch (IOException ex) {
Logger.getLogger(SocialMediaList.class.getName()).log(Level.SEVERE, null, ex);
}
case "Exit":
System.exit(0);
}
}
}
class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}

Opening, Editing and Saving text in JTextArea to .txt file

I am messing around with java swing and am trying to open a text file containing existing data with a JTextArea. It doesn't seem to be saving any changes regardless of the different things I have tried.
Below is code that reads the text file fine, but doesn't write it (obviously).
If someone could please advise me as to how I could successfully save changes to the JTextArea I would be greatful.
package funwithswing;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AllDataGUI extends JFrame{
public AllDataGUI(){
fileRead();
panels();
}
private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
private JTextArea textArea = new JTextArea(storeAllString,0,70);
private JButton getCloseButton(){
return closeButton;
}
private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
private void fileWrite(){
try{
FileWriter write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void saveBtn(){
}
}
You need to close FileWriter. Use try-with-resource of Java-7 or finally block to close resource properly.
private void fileWrite(){
FileWriter write=null;
try{
write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
finally{
if(write != null)
write.close();
}
}
There are some mistakes in your code, I have modified those. Compile and run the below code This will solv your problem.
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AllDataGUI extends JFrame{
public AllDataGUI(){
fileRead();
panels();
}
private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
// private JTextArea textArea = new JTextArea(storeAllString,0,70);
private JTextArea textArea = new JTextArea();
private JButton getCloseButton(){
return closeButton;
}
private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
textArea.setText(storeAllString);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
// JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
saveCloseBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveBtn();
frame.dispose();
}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void saveBtn(){
File file = null;
FileWriter out=null;
try {
file = new File("CompleteData.txt");
out = new FileWriter(file);
out.write(textArea.getText());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] arg)
{
new AllDataGUI();
}
}

Form that has either a Comic Book object or a Novel object

Sorry if I'm double positing but I totally suck at Java.
I am trying to make my form have the ability to change dynamically if you select a radio button. The functions save, delete, new will remain the same but the contents of the body e.g. the UPC will change to ISBN of the novel and the other fields.
Is there a way to when you press Novel to load the items from Novel to replace Comic book items?
I tried to separate but I've hit a block and with my limited skills unsure what to do.
I just want it to be able to change it so that it works.
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
public class FormFictionCatelogue extends JFrame implements ActionListener {
// Constants
// =========
private final String FORM_TITLE = "Fiction Adiction Catelogue";
private final int X_LOC = 400;
private final int Y_LOC = 80;
private final int WIDTH = 600;
private final int HEIGHT = 450;
private String gradeCode;
//final static String filename = "data/comicBookData.txt";
private JButton firstPageButton;
private JButton backPageButton;
private JButton forwardPageButton;
private JButton lastPageButton;
private JRadioButton comicBookRadioButton;
private JRadioButton novelRadioButton;
private final String FIRSTPAGE_BUTTON_TEXT = "|<";
private final String BACKPAGE_BUTTON_TEXT = "<";
private final String FORWARDPAGE_BUTTON_TEXT = ">";
private final String LASTPAGE_BUTTON_TEXT = ">|";
private final String COMICBOOK_BUTTON_TEXT = "Comic";
private final String NOVEL_BUTTON_TEXT = "Novel";
private final String SAVE_BUTTON_TEXT = "Save";
private final String EXIT_BUTTON_TEXT = "Exit";
private final String CLEAR_BUTTON_TEXT = "Clear";
private final String FIND_BUTTON_TEXT = "Find";
private final String DELETE_BUTTON_TEXT = "Delete";
private final String ADDPAGE_BUTTON_TEXT = "New";
// Attributes
private JTextField upcTextField;
private JTextField isbnTextField;
private JTextField titleTextField;
private JTextField issueNumTextField;
private JTextField bookNumTextField;
private JTextField writerTextField;
private JTextField authorTextField;
private JTextField artistTextField;
private JTextField publisherTextField;
private JTextField seriesTextField;
private JTextField otherBooksTextField;
private JTextField gradeCodeTextField;
private JTextField charactersTextField;
private JButton saveButton;
private JButton deleteButton;
private JButton findButton;
private JButton clearButton;
private JButton exitButton;
private JButton addPageButton;
FictionCatelogue fc;
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) {
try {
FormFictionCatelogue form = new FormFictionCatelogue();
form.fc = new FictionCatelogue();
form.setVisible(true);
//comicBook selected by default
form.populatefields(form.fc.returnComic(0));
//if novel is selected change fields to novel and populate
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
/**
*
*/
public FormFictionCatelogue() {
// Set form properties
// ===================
setTitle(FORM_TITLE);
setSize(WIDTH, HEIGHT);
setLocation(X_LOC, Y_LOC);
// Create and set components
// -------------------------
// Create panels to hold components
JPanel menuBarPanel = new JPanel();
JPanel fieldsPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
JPanel navigationPanel = new JPanel();
//JPanel radioButtonsPanel = new JPanel();
ButtonGroup bG = new ButtonGroup();
// Set the layout of the panels
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
// Menu
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu about = new JMenu("About");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem eMenuItem1 = new JMenuItem("Reports", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Reports are located here");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//calls reports
//System.exit(0);
}
});
file.add(eMenuItem);
about.add(eMenuItem1);
menubar.add(file);
menubar.add(about);
setJMenuBar(menubar);
setTitle("Menu");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//if comic is selected
ComicBookFields(fieldsPanel);
//else
//NovelFields(fieldsPanel);
// Buttons
comicBookRadioButton = new JRadioButton(COMICBOOK_BUTTON_TEXT);
novelRadioButton = new JRadioButton(NOVEL_BUTTON_TEXT);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
this.setLayout(new FlowLayout());
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
addPageButton = new JButton(ADDPAGE_BUTTON_TEXT);
buttonsPanel.add(addPageButton);
saveButton = new JButton(SAVE_BUTTON_TEXT);
buttonsPanel.add(saveButton);
clearButton = new JButton(CLEAR_BUTTON_TEXT);
buttonsPanel.add(clearButton);
deleteButton = new JButton(DELETE_BUTTON_TEXT);
buttonsPanel.add(deleteButton);
findButton = new JButton(FIND_BUTTON_TEXT);
buttonsPanel.add(findButton);
exitButton = new JButton(EXIT_BUTTON_TEXT);
buttonsPanel.add(exitButton);
firstPageButton = new JButton(FIRSTPAGE_BUTTON_TEXT);
navigationPanel.add(firstPageButton);
backPageButton = new JButton(BACKPAGE_BUTTON_TEXT);
navigationPanel.add(backPageButton);
forwardPageButton = new JButton(FORWARDPAGE_BUTTON_TEXT);
navigationPanel.add(forwardPageButton);
lastPageButton = new JButton(LASTPAGE_BUTTON_TEXT);
navigationPanel.add(lastPageButton);
// Get the container holding the components of this class
Container con = getContentPane();
// Set layout of this class
con.setLayout(new BorderLayout());
con.setLayout( new FlowLayout());
// Add the fieldsPanel and buttonsPanel to this class.
// con.add(menuBarPanel, BorderLayout);
con.add(fieldsPanel, BorderLayout.CENTER);
con.add(buttonsPanel, BorderLayout.LINE_END);
con.add(navigationPanel, BorderLayout.SOUTH);
//con.add(radioButtonsPanel, BorderLayout.PAGE_START);
// Register listeners
// ==================
// Register action listeners on buttons
saveButton.addActionListener(this);
clearButton.addActionListener(this);
deleteButton.addActionListener(this);
findButton.addActionListener(this);
exitButton.addActionListener(this);
firstPageButton.addActionListener(this);
backPageButton.addActionListener(this);
forwardPageButton.addActionListener(this);
lastPageButton.addActionListener(this);
addPageButton.addActionListener(this);
comicBookRadioButton.addActionListener(this);
novelRadioButton.addActionListener(this);
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Radiobutton (){
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
this.setVisible(true);
}
// Populate the fields at the start of the application
public void populatefields(ComicBook cb) {
String gradecode;
// radio button selection = comic do this
if (cb != null) {
upcTextField.setText(cb.getUpc());
titleTextField.setText(cb.getTitle());
issueNumTextField.setText(Integer.toString(cb.getIssuenumber()));
writerTextField.setText(cb.getWriter());
artistTextField.setText(cb.getArtist());
publisherTextField.setText(cb.getPublisher());
gradecode = cb.getGradeCode();
gradeCodeTextField.setText(cb.determineCondition(gradecode));
charactersTextField.setText(cb.getCharacters());
}
//radio button selection = novel do this
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
public void actionPerformed(ActionEvent ae) {
try {
if(ae.getActionCommand().equals(COMICBOOK_BUTTON_TEXT)){
//FormFictionCatelogue form = new FormFictionCatelogue();
//form.populatefields(form.fc.returnObject(0));
//ComicBookFields(fieldsPanel);
populatefields(fc.returnComic(0));
} else if (ae.getActionCommand().equals(NOVEL_BUTTON_TEXT)) {
} else if (ae.getActionCommand().equals(SAVE_BUTTON_TEXT)) {
save();
} else if (ae.getActionCommand().equals(CLEAR_BUTTON_TEXT)) {
clear();
} else if (ae.getActionCommand().equals(ADDPAGE_BUTTON_TEXT)) {
add();
} else if (ae.getActionCommand().equals(DELETE_BUTTON_TEXT)) {
delete();
} else if (ae.getActionCommand().equals(FIND_BUTTON_TEXT)) {
find();
} else if (ae.getActionCommand().equals(EXIT_BUTTON_TEXT)) {
exit();
} else if (ae.getActionCommand().equals(FIRSTPAGE_BUTTON_TEXT)) {
// first record
populatefields(fc.firstRecord());
} else if (ae.getActionCommand().equals(FORWARDPAGE_BUTTON_TEXT)) {
// next record
populatefields(fc.nextRecord());
} else if (ae.getActionCommand().equals(BACKPAGE_BUTTON_TEXT)) {
// previous record
populatefields(fc.previousRecord());
} else if (ae.getActionCommand().equals(LASTPAGE_BUTTON_TEXT)) {
// last record
populatefields(fc.lastRecord());
} else {
throw new Exception("Unknown event!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
void clear() {
upcTextField.setText("");
titleTextField.setText("");
issueNumTextField.setText("");
writerTextField.setText("");
artistTextField.setText("");
gradeCodeTextField.setText("");
publisherTextField.setText("");
charactersTextField.setText("");
}
private void exit() {
System.exit(0);
}
void add() {
try{
clear();
ComicBook cb = new ComicBook();
fc.add(cb);
fc.lastRecord();
} catch (Exception e){
e.printStackTrace();
}
}
void save() throws Exception {
// if radio button = comic do this
ComicBook cb = new ComicBook();
String condition;
if (upcTextField.getText().length() == 16) {
//searches if there is another record if()
cb.setUpc(upcTextField.getText());
} else {
throw new Exception("Upc is not at required length ");
}
cb.setTitle(titleTextField.getText());
cb.setIssuenumber(Integer.parseInt(issueNumTextField.getText()));
cb.setWriter(writerTextField.getText());
cb.setArtist(artistTextField.getText());
cb.setPublisher(publisherTextField.getText());
condition = cb.determineString(gradeCodeTextField.getText());
if (condition.equals("Wrong Input")) {
throw new Exception("Grade code is not valid");
} else {
cb.setGradeCode(condition);
}
cb.setCharacters(charactersTextField.getText());
fc.save(cb);
// if radio button = novels do this
}
private void delete() throws Exception {
fc.delete();
populatefields(fc.getCurrentRecord());
}
private void find() {
// from
// http://www.roseindia.net/java/example/java/swing/ShowInputDialog.shtml
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
"Comic Book Search", 1);
if (str != null) {
ComicBook cb = new ComicBook();
cb = fc.search(str);
if (cb != null) {
populatefields(cb);
} else {
JOptionPane.showMessageDialog(null, "No comic books found ",
"Comic Book Search", 1);
}
}
}
public JPanel ComicBookFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("UPC: "));
upcTextField = new JTextField(20);
fieldsPanel.add(upcTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Issue Number: "));
issueNumTextField = new JTextField(20);
fieldsPanel.add(issueNumTextField);
fieldsPanel.add(new JLabel("Writer: "));
writerTextField = new JTextField(20);
fieldsPanel.add(writerTextField);
fieldsPanel.add(new JLabel("Artist: "));
artistTextField = new JTextField(20);
fieldsPanel.add(artistTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Grade Code: "));
gradeCodeTextField = new JTextField(20);
fieldsPanel.add(gradeCodeTextField);
fieldsPanel.add(new JLabel("Characters"));
charactersTextField = new JTextField(20);
fieldsPanel.add(charactersTextField);
return fieldsPanel;
}
public JPanel NovelFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("ISBN: "));
isbnTextField = new JTextField(20);
fieldsPanel.add(isbnTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Book Number: "));
bookNumTextField = new JTextField(20);
fieldsPanel.add(bookNumTextField);
fieldsPanel.add(new JLabel("Author: "));
authorTextField = new JTextField(20);
fieldsPanel.add(authorTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Series: "));
seriesTextField = new JTextField(20);
fieldsPanel.add(seriesTextField);
fieldsPanel.add(new JLabel("Other Books"));
otherBooksTextField = new JTextField(20);
fieldsPanel.add(otherBooksTextField);
return fieldsPanel;
}
}
To swap forms you can use a CardLayout.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example from the tutorial switches when you make a selection from a combo box. In your case you would change the panel when you click on the radio button. So you might also want to read the section from the tutorial on How to Use Buttons.
Otherwise you can switch JPanels on JRadioButton selection like this:
You've got a JPanel called displayPanel which contains the ComicPanel by default, if you select the Novel RadioButton the displayPanel gets cleared and the NovelPanel will be added.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class AddNovelOrComicPanel extends JPanel implements ActionListener {
private JPanel selectPanel;
private JPanel displayPanel;
private JPanel buttonPanel;
private JRadioButton comic;
private JRadioButton novel;
// we need this ButtonGroup to take care about unselecting the former selected JRadioButton
ButtonGroup radioButtons;
public AddNovelOrComicPanel() {
this.setLayout(new BorderLayout());
initComponents();
this.add(selectPanel, BorderLayout.NORTH);
this.add(displayPanel, BorderLayout.CENTER);
}
/**
* Initializes all Components
*/
private void initComponents() {
selectPanel = new JPanel(new GridLayout(1, 2));
comic = new JRadioButton("Comic");
comic.setSelected(true);
comic.addActionListener(this);
novel = new JRadioButton("Novel");
novel.addActionListener(this);
radioButtons = new ButtonGroup();
radioButtons.add(comic);
radioButtons.add(novel);
selectPanel.add(comic);
selectPanel.add(novel);
displayPanel = new JPanel();
displayPanel.add(new ComicPanel());
}
#Override
public void actionPerformed(ActionEvent e) {
// if comic is selected show the ComicPanel in the displayPanel
if(e.getSource().equals(comic)) {
displayPanel.removeAll();
displayPanel.add(new ComicPanel());
}
// if novel is selected show the NovelPanel in the displayPanel
if(e.getSource().equals(novel)) {
displayPanel.removeAll();
displayPanel.add(new NovelPanel());
}
// revalidate all to show the changes
revalidate();
}
}
/**
* The NovelPanel class
* it contains all the Items you need to register a new Novel
*/
class NovelPanel extends JPanel {
public NovelPanel() {
this.add(new JLabel("Add your Novel components here"));
}
}
/**
* The ComicPanel class
*/
class ComicPanel extends JPanel {
public ComicPanel() {
this.add(new JLabel("Add your Comic components here"));
}
}
So it is your choice what you want to do. Possible is nearly everything ;)
Patrick

How to change frame's title when an internal or external drag and drop event occures

i don't know how to change frame's title when an drag and drop event takes place. I 've read Java Docs about DnD and Transferable but i can't find a solution, i've come to an conclusion that i have to play games with DropTargetListener, but i am to a deadlock.Any answer would be a relief!(also in drag n drop i would like to hold the attributes of the text)
The SSCCE is:
package sscceeditor;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.BadLocationException;
import rtf.AdvancedRTFDocument;
import rtf.AdvancedRTFEditorKit;
class ExampleFrame extends JFrame{
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadItem = new JMenuItem("Load");
private JTextPane txtPane = new JTextPane(new AdvancedRTFDocument());
private JScrollPane scroller = new JScrollPane(txtPane);
private JFileChooser chooser = new JFileChooser();
private AdvancedRTFEditorKit rtfKit = new AdvancedRTFEditorKit();
//ctor begins...
public ExampleFrame(){
super("Example Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 400);
this.setLocationRelativeTo(null);
saveItem.addActionListener(new SaveHandler());
loadItem.addActionListener(new LoadHandler());
this.addDragAndDropSupportToJTextPane(txtPane);
//set the kit...
txtPane.setEditorKit(rtfKit);
//create the menu...
fileMenu.add(saveItem);
fileMenu.add(loadItem);
bar.add(fileMenu);
this.setJMenuBar(bar);
//create the main panel...
JPanel mainPane = new JPanel();
mainPane.setLayout(new BorderLayout());
mainPane.add(BorderLayout.CENTER , scroller);
this.setContentPane(mainPane);
}//end of ctor.
//inner event handler classes...
class SaveHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showSaveDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
try(BufferedWriter bw = new BufferedWriter(
new FileWriter(chooser.getSelectedFile().getPath())))
{
rtfKit.write(bw, txtPane.getDocument(), 0, txtPane.getDocument().getLength());
bw.close();
JOptionPane.showMessageDialog( ExampleFrame.this,"Saved");
txtPane.setText("");
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
class LoadHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showOpenDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
StringBuilder sb = new StringBuilder();
try(BufferedReader bw = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath())))
{
txtPane.setText("");
rtfKit.read(bw, txtPane.getDocument(), 0);
bw.close();
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
private void addDragAndDropSupportToJTextPane(JTextPane thePane){
thePane.setDragEnabled(true);
thePane.setDropMode(DropMode.INSERT);
}//end of method.
}//end of class ExampleFrame.
public class SSCCEeditor {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new ExampleFrame().setVisible(true);
}
});
}
}
Thanks a lot for your time!

Categories