How to draw line graph in Java from text file? [duplicate] - java

I have written a Java GUI program which opens a text file and reads the data in the left panel. Now I want to display a graph of the data read from the same file on the right panel.
I have used JFileChooser to open files and read the data and display them on a text area. I want the data read from the file to be displayed using a two dimensional X-Y graph. The axis of the graph should be labeled using the label information specified in the data file. The values on the X-axis should begin from the x-axis start value specified, with intervals which increment at a rate determined by the x-axis interval value. The values on the Y-axis will need to be determined from the data itself. Each point plotted on the graph should be joined using a single line.
I have used several methods but none worked. I have tried reading each line on the text file as arrays and use the arrays as the dataset, but it didn't work as well. Please help me plot a graph from the data on the text file. Any help would be appreciated. Thanks.
P.S The graph should be plotted using AWT/Swing libraries only.
The data on the file is as follows:
Title: Effect of Age on Ability
Xlabel: Age
Ylabel: Ability
start: 0
interval: 15
0, 3, 4.2, 7, 5.1, 10, 3.2
Following are my code which I have written so far:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
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.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
#SuppressWarnings("serial")
public class GUI extends JFrame {
private String[] readLines = new String[6];
public GUI() {
// Setting Title, size and layout
setTitle("Data Visualiser");
setSize(950, 1000);
setLayout(new BorderLayout());
// Creates a menubar for a JFrame
final JMenuBar menuBar = new JMenuBar();
// Add the menubar to the frame
setJMenuBar(menuBar);
// Define and add two drop down menu to the menubar, "file" and "help"
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
// adding menu items and icons to the "file" drop down menu,
final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));
final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));
final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));
final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));
//////////////////////////////////////////////////////////////////////////////////////////////
// Create a text area.
final JTextArea textArea = new JTextArea("");
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
// textArea.add(textScrollPane, BorderLayout.CENTER); //add the
// JScrollPane to the panel
// Scrollbars
textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textScrollPane.setPreferredSize(new Dimension(350, 550));
textScrollPane.setBorder(
BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
// Create an graphics pane.
JPanel graphicsArea = new JPanel();
//graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));
JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);
// Scrollbars
graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setPreferredSize(new Dimension(550, 550));
graphicsScrollPane.setBorder(
BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
// Put the graphics pane and the text pane in a split pane.
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
JPanel rightPane = new JPanel(new GridLayout(1, 0));
rightPane.add(splitPane);
// Put everything together.
JPanel leftPane = new JPanel(new BorderLayout());
add(rightPane, BorderLayout.LINE_END);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// file menu shortcut
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
// openAction.addActionListener(this);
openAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
// using JFileChooser to open the text file
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
// fileChooser.setCurrentDirectory(new
// File(System.getProperty("user.home"))); // setting
// current
// directory
File file = fileChooser.getSelectedFile();
BufferedReader br = null;
try {
// FileReader fr = new FileReader(file);
Scanner f = new Scanner(file);
for (int i = 0; i < 6; i++) {
readLines[i] = f.nextLine();
textArea.setText(textArea.getText() + readLines[i] + "\n");
String array[] = readLines[i].split(" ");
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "File not found!", "ERROR!",
JOptionPane.ERROR_MESSAGE); // error message
// if file not
// found
} catch (NullPointerException e) {
// System.out.println(e.getLocalizedMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
// exit button shortcut
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
// setting up exit button
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
// about button shortcut
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
// clicking on about button opens up a dialog box which contain
// information about the program
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(menuBar.getComponent(0),
"This program is based on the development of a data visualization tool. \n"
+ "The basic concept is to produce a piece of software which reads in raw textual data, \n"
+ "analyses that data, then presents it graphically to the user.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
}
}

Starting from your example, note the following:
Use a ChartPanel for your graphicsArea; then, your openAction() can simply invoke setChart().
Parse the chosen file in creatChart(); the title and data lines are shown, but the remaining attributes are left as an exercise.
Consider using Properties for your file format;
For greater flexibility, use Action as shown here.
To change the chart panel's default size, override getPreferredSize() as shown here.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
P.S. The graph should be plotted using AWT/Swing libraries only.
For a single chart, replace ChartPanel with JPanel and override paintComponent() to perform the rendering. You can transform coordinates using the approach is outlined here or here.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
//* #see https://stackoverflow.com/a/36764715/230513 */
public class GUI extends JFrame {
public GUI() {
super("Data Visualiser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));
final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));
final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));
final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));
final JTextArea textArea = new JTextArea(8, 16);
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
textScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
ChartPanel graphicsArea = new ChartPanel(null);
graphicsArea.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.LINE_END);
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
openAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
JFileChooser fileChooser = new JFileChooser(new File("."));
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
graphicsArea.setChart(creatChart(file));
}
}
}
private JFreeChart creatChart(File file) {
String title = null;
String xAxisLabel = null;
String yAxisLabel = null;
BufferedReader in = null;
int start = 0;
int interval = 0;
String data = null;
String line = null;
try {
in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null) {
textArea.append(line + "\n");
if (line.startsWith("Title")) {
title = line.split(":")[1].trim();
}
// parse other lines here
if (!line.contains(":")) {
data = line;
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
XYSeries dataset = new XYSeries(file.getName());
for (String s : data.split(",")) {
dataset.add(start, Double.valueOf(s));
start += interval;
}
return ChartFactory.createXYLineChart(title,
xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null,
"Visualization tool.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new GUI();
});
}
}

Related

How to read plain text file using RTFEditorKit?

I am creating a simple Wordpad editor application. I am using JTextPane. I have added code to read '.rtf' file using RTFEditorKit. Initialization code:
RTFEditorKit rtfKit = new RTFEditorKit();
JTextPane textPane = new JTextPane();
textPane.setEditorKit(rtfKit);
Now I need to read plain text file '.txt' using 'RTFEditorKit' into the same JTextPane, so that I can view plain text file and rtf file in the same application. How can I achieve this?
My application minimal code:
import static java.awt.event.InputEvent.CTRL_DOWN_MASK;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import javax.swing.JFileChooser;
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.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Document;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
public class MyNotepad implements ActionListener {
public JFrame frame;
public JPanel panel;
public JTextPane textPane;
public RTFEditorKit rtf;
public StyleContext styleContext;
public Document document;
public JScrollPane scrollPane;
public JMenuBar menuBar;
public JMenu fileMenu;
public JMenuItem newSubMenu;
public JMenuItem openSubMenu;
public JFileChooser fc;
public boolean openFileExtFlag = true;
public boolean saveFileExtFlag = true;
public File openFile;
public File saveFile;
public boolean saveWindowTitle = false;
public boolean openFileFlag;
public boolean saveFileFlag;
public boolean saved = true;
public boolean dontSaveOption;
public BufferedReader br;
public boolean saveForNewOpenExitListener;
public boolean saveAsFlag;
public int returnVal;
public String filePath;
public boolean flagForOpenListener;
public StyledDocument styledDocument;
public Style defaultStyle;
public MutableAttributeSet mas;
public MyNotepad() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
frame = new JFrame("My Notepad");
panel = new JPanel(new BorderLayout());
rtf = new RTFEditorKit();
textPane = new JTextPane();
textPane.setEditorKit(rtf);
textPane.setMargin(new Insets(10,5,5,5));
styleContext = new StyleContext();
mas = textPane.getInputAttributes();
styledDocument = textPane.getStyledDocument();
textPane.setDocument(styledDocument);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(textPane);
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
newSubMenu = new JMenuItem("New");
newSubMenu.setAccelerator(KeyStroke.getKeyStroke('N', CTRL_DOWN_MASK));
openSubMenu = new JMenuItem("Open...");
openSubMenu.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK));
defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
fc= new JFileChooser();
openSubMenu.addActionListener(this);
newSubMenu.addActionListener(this);
scrollPane.setPreferredSize(new Dimension(700,500));
fileMenu.add(newSubMenu);
fileMenu.add(openSubMenu);
menuBar.add(fileMenu);
textPane.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(new JLabel(" "), BorderLayout.EAST);
panel.add(new JLabel(" "), BorderLayout.WEST);
panel.add(new JLabel(" "), BorderLayout.SOUTH);
frame.setJMenuBar(menuBar);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(900,200));
frame.pack();
textPane.requestFocus();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyNotepad();
}
public void actionPerformed(ActionEvent ae) {
if ((ae.getSource() == openSubMenu)) {
openActionListener();
}
}
public boolean openActionListener() {
if (openFileExtFlag && saveFileExtFlag) {
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new FileNameExtensionFilter("Rich Text File (*.rtf)", "rtf"));
fc.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
openFileExtFlag = false;
}
do {
returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
openFile = fc.getSelectedFile();
filePath = openFile.getPath();
if (openFile.exists()) {
break;
}
JOptionPane.showMessageDialog(frame, "File not found, please verify the file name and the path", "Cannot open", JOptionPane.OK_OPTION);
} else {
return false;
}
} while (true);
try {
System.out.println("---opening document...");
textPane.setText("");
InputStream in = new FileInputStream(filePath);
System.out.println("Opening file - " + filePath);
if (filePath.endsWith(".rtf")) {
rtf.read(in, textPane.getDocument(), 0);
in.close();
} else if (filePath.endsWith(".txt")) {
textPane = new JTextPane();
FileReader fileReader = new FileReader(filePath);
textPane.read(fileReader, openFile);
fileReader.close();
}
textPane.requestFocus();
textPane.setCaretPosition(0);
frame.setTitle("My Notepad " + "- " + filePath);
System.out.println("----File opened successfully");
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Cannot open, Invalid RTF file", "Cannot open", JOptionPane.OK_OPTION);
}
return true;
}
}
textPane = new JTextPane();
FileReader fileReader = new FileReader(filePath);
textPane.read(fileReader, openFile);
fileReader.close();
You are creating a new JTextPane which will never be added to the UI, and the text is added inside this very textPane instead of the one you see in the UI...
Just remove the line : textPane = new JTextPane();
Sorry for late answer.

open another class with an action listener

Hi im currently working on a program but I need to be able to change the class (so that the frame changes) with just the click of a menu tab.
I would like someone to modify this to get my to class2.java
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
class 1.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class circle_ac {
private JFrame frame;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
circle_ac window = new circle_ac();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public circle_ac() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame = new JFrame();
frame.setResizable(true);
frame.setBounds(1000, 1000, 2250, 1000);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,frame1);
this.revalidate();
this.repaint();
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
/*setup calculate button*/
JButton btnCalculate = new JButton("calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*setup calculations*/
double rad;
double ans1;
double ans2;
double pi=3.1415926535897932384626433832795;
try {
rad=Double.parseDouble(txtRadius.getText()) ;
ans1= pi*(rad*rad);
ans2= 2*pi*rad;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(25);
txtTheAreaOf.setText("The Area Is "+df.format(ans1));
txtTheCircumfrenceOf.setText("The Circumference Is "+df.format(ans2) );
/*setup error message*/
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please Enter Valid Radius");
}
}
});
/*initialize calculate button*/
btnCalculate.setFont(new Font("Tahoma", Font.PLAIN, 60));
btnCalculate.setBackground(new Color(227, 227, 227));
btnCalculate.setForeground(Color.BLACK);
frame.getContentPane().add(btnCalculate, BorderLayout.SOUTH);
/*setup Radius text box*/
txtRadius = new JTextField();
txtRadius.setFont(new Font("Tahoma", Font.PLAIN, 55));
txtRadius.setCursor(null);
txtRadius.setInputVerifier(null);
txtRadius.setText(" Enter The Radius");
txtRadius.setBackground(SystemColor.controlHighlight);
frame.getContentPane().add(txtRadius, BorderLayout.CENTER);
txtRadius.setColumns(10);
/*setup Area text box*/
txtTheAreaOf = new JTextField();
txtTheAreaOf.setEditable(false);
txtTheAreaOf.setText("The Area Of The Circle Is ");
txtTheAreaOf.setBackground(SystemColor.control);
txtTheAreaOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
frame.getContentPane().add(txtTheAreaOf, BorderLayout.WEST);
/*setup Circumference text box*/
txtTheCircumfrenceOf =new JTextField();
txtTheAreaOf.setEditable(false);
txtTheCircumfrenceOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
txtTheCircumfrenceOf.setText("The Circumfrence Of The Circle Is ");
txtTheCircumfrenceOf.setBackground(SystemColor.control);
frame.getContentPane().add((Component) txtTheCircumfrenceOf, BorderLayout.EAST);
}
}
class2.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class area_c {
private JFrame frame1;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
area_c window = new area_c();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public area_c() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame1 = new JFrame();
frame1.setResizable(true);
frame1.setBounds(1000, 1000, 2250, 1000);
frame1.pack();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
frame1.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame1.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
System.out.println("Hello World!");
I need the menu tab to change it from class1.java to class2.java with an action listener.
is this possible, if so how do I do it.
I recommend to implement your two classes as JPanels. Then you can add these JPanels to your JFrame. Have a look at this small example, that shows the principle in a short and quick way. Hope it helps:
package test;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class TestFrame extends JFrame {
private Container contentPane;
private JPanel panel1,panel2;
public TestFrame() {
super("Test");
this.setJMenuBar(menubar());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = this.getContentPane();
createPanels();
contentPane.setLayout(new BorderLayout());
this.add(BorderLayout.CENTER,panel1);
this.pack();
this.setVisible(true);
}
private JMenuBar menubar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem m1 =new JMenuItem("Selection 1");
JMenuItem m2 =new JMenuItem("Selection 2");
m1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
refresh();
}
});
m2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
refresh();
}
});
fileMenu.add(m1);
fileMenu.add(m2);
menubar.add(fileMenu);
return menubar;
}
private void refresh() {
this.revalidate();
this.repaint();
}
private void createPanels() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(BorderLayout.CENTER,new JLabel("Hello World"));
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.CENTER,new JLabel("Goodbye World"));
}
public static void main(String[] args) {
TestFrame t = new TestFrame();
}
}
In most of the IDE's, when you right-click on the Button in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
When you are in one frame, you can set it's visibility off to hide it, like this:
this.setVisible(false);
And you can create the object of another class (of the other frame where you want to redirect) and set it's visibility on to display it, like this:
area_c of = new area_c();
of.setVisible(true);
So, you will be transitioning from one class to another of different frames.
You can achieve the same using the object of JMenuItem object:
class1 = new JPanel();
class1.setLayout(new BorderLayout());
class1.add(BorderLayout.CENTER,new JLabel("Label_Name"));
class2 = new JPanel();
class2.setLayout(new BorderLayout());
class2.add(BorderLayout.CENTER,new JLabel("Label_Name"));
JMenuItem JMenuItemObject1 =new JMenuItem("Class 1");
JMenuItem JMenuItemObject2 =new JMenuItem("Class 2");
JMenuItemObject1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
this.revalidate();
this.repaint();
}
});
JMenuItemObject2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
this.revalidate();
this.repaint();
}
});
area.add(JMenuItemObject1);
area.add(JMenuItemObject2);
menubar.add(area);

How to save a in-application edited txt file in java

I'm stuck on how to save a file in a text editor i'm creating.Here's my code if you can help me
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
public class test1 {
public static void main ( String[] args )
{
JButton b1 = new JButton("Press to read a file");
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Text Reading Box" ) );
// create the middle panel components
final JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false);
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Text area in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ("Text Reader 0.4 Beta");
frame.add ( middlePanel );
frame.add(b1, BorderLayout.NORTH);
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible ( true );
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch(Exception error) {
System.err.println("Could'nt read a file");
}
}
});
}
}
I guess you should have another button say 'Save' to save your edited content back to the file. For that you have to handle action on save button and write contents back to the file.
package com.test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class Random
{
public static void main(String[] args)
{
JButton b1 = new JButton("Press to read a file");
JButton b2 = new JButton("Save");
JPanel middlePanel = new JPanel();
final StringBuilder filename = new StringBuilder("");
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Text Reading Box"));
// create the middle panel components
final JTextArea display = new JTextArea(16, 58);
display.setEditable(true);
JScrollPane scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// Add Text area in to middle panel
middlePanel.add(scroll);
// My code
JFrame frame = new JFrame("Text Reader 0.4 Beta");
frame.add(middlePanel);
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename.append(f.getAbsolutePath());
try
{
FileReader reader = new FileReader(filename.toString());
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch (Exception error)
{
System.err.println("Could'nt read a file");
}
}
});
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textToSet = display.getText();
try
{
PrintWriter writer = new PrintWriter(filename.toString(), "UTF-8");
writer.write(textToSet);
writer.close();
}
catch (FileNotFoundException | UnsupportedEncodingException exc)
{
System.err.println("Could'nt write to the file");
}
}
});
}
}

How can I have a writable text box?

Using pure java, I would like to have a player press a JButton, have a text box pop up which they can type in, and then have a certain action happen when the player presses "Enter".
How could I do this?
I have not yet attempted this because I do not know where to start, however my current code is
package Joehot200;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main extends JFrame {
static boolean start = false;
private JPanel contentPane;
/**
* Launch the application.
*/
static Main frame = null;
String version = "0.4";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
frame.setTitle("Privateers");
} catch (Exception e) {
e.printStackTrace();
}
}
});
TerrainDemo.startGame();
}
boolean cantConnect = false;
/**
* Create the frame.
*/
public Main() {
setExtendedState(JFrame.MAXIMIZED_BOTH);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
final JButton btnEnterBattlefield = new JButton("Enter battlefield!");
btnEnterBattlefield.setForeground(Color.red);
//btnEnterBattlefield.setBackground(Color.green);
//btnEnterBattlefield.setOpaque(true);
menuBar.add(btnEnterBattlefield);
btnEnterBattlefield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println(new File(System.getProperty("user.dir") + "res/images/heightmap.bmp").getAbsolutePath());
//System.out.println("You clicked the button");
if (cantConnect){
btnEnterBattlefield.setText("Unable to connect to the server!");
}else{
btnEnterBattlefield.setText("Connecting to server...");
}
start = true;
}
});
//JMenu mnLogIn = new JMenu("Log in");
JMenu mnLogIn = new JMenu("Currently useless button");
mnLogIn.setForeground(Color.magenta);
menuBar.add(mnLogIn);
JButton btnLogIntoGame = new JButton("Log into game.");
mnLogIn.add(btnLogIntoGame);
JButton btnRegisterNewAccount = new JButton("Register new account");
mnLogIn.add(btnRegisterNewAccount);
final JButton btnGoToWebsite = new JButton("We currently do not but soon will have a website.");
btnGoToWebsite.setForeground(Color.BLUE);
//btnGoToWebsite = new JButton("Go to website.");
btnGoToWebsite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Going to website!");
try {
java.awt.Desktop.getDesktop().browse(new URI("www.endcraft.net/none"));
} catch (Exception e1) {
btnGoToWebsite.setText("Error going to website!");
}
}
});
menuBar.add(btnGoToWebsite);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
FlowLayout flowLayout = (FlowLayout) contentPane.getLayout();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = img.getScaledInstance(this.getWidth()*3, this.getHeight()*3, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
getContentPane().add(background);
background.setLayout(new FlowLayout());
//JProgressBar progressBar = new JProgressBar();
//contentPane.add(progressBar);
//JMenu mnWelcomeToA = new JMenu("Welcome to a pirate game!");
//contentPane.add(mnWelcomeToA);
//JButton btnStartGame = new JButton("Start game");
//mnWelcomeToA.add(btnStartGame);
//JSplitPane splitPane = new JSplitPane();
//mnWelcomeToA.add(splitPane);
//JButton btnRegister = new JButton("Register");
//splitPane.setLeftComponent(btnRegister);
//JButton btnLogin = new JButton("Login");
//splitPane.setRightComponent(btnLogin);
}
}
It is the "Register account" and "Log into game" button that I would like to have the above described action happen on.
Would be great if someone could tell me how to do this.
If you decide to implement a new frame (not best practice), with a new panel, and the JTextField or JTextArea within, you must bind a listener to the button that calls setVisible() on the newly created frame..
For example:
public void actionPerformed(ActionEvent e) {
yourFrame.setVisible(true);
}
Further, you could create the frame everytime the button is clicked, within the actionPerformed method aswell, however this is also not best practice..
A better alternative may be to implement a JOptionPane, see here or here..

How to rectify this program?

This is a program to display a pie chart. I also have a button. But the program I have written, creates two separate frames and one frame is for the pie chart and the other is for the button. How do I put both button and pie chart on the same frame?? Can you please rectify my program.
import java.awt.*;
import org.jfree.chart.*;
import org.jfree.chart.title.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class Pie{
public static void getFile(File f)
{
System.out.println("File is: "+f.getName());
}
public static void main(String[] args)
{
JPanel panel=new JPanel();
panel.setLayout(null);
JButton b=new JButton("Open File");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser=new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
getFile(file);
}
}
}
);
b.setBounds(50,40,100,35);
panel.add(b);
DefaultPieDataset pieDataset = new DefaultPieDataset();
ieDataset.setValue("A", new Integer(10));
pieDataset.setValue("B", new Integer(20));
pieDataset.setValue("C", new Integer(30));
pieDataset.setValue("D", new Integer(10));
pieDataset.setValue("E", new Integer(20));
pieDataset.setValue("F", new Integer(10));
FreeChart chart = ChartFactory.createPieChart("Pie Chart using JFreeChart", pieDataset, true,true,true);
ChartFrame frame1=new ChartFrame("Pie Chart",chart);
frame1.add(panel);
frame1.setVisible(true);
frame1.setSize(600,600);
}
}
Don't use absolute layout unless it is really necessary. Rely on layout managers, pref/min/max size and constraints to size and position components. This also means that you should not call setBounds/setSize/setLocation on components, let the layout manager do this for you.
Init the UI from the EDT (Event dispatching tread)
You don't do anything with your FileChooser currently
Try to avoid static and instead use new Something()
Don't use new Integer() but rather use Integer.valueOf() (and this is valid for all the primitive wrapping classes, Boolean, Short, Long, ...)
I am not sure how you get two frames, but I got your code working by modifying it this way.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class Pie {
private static void initUI() {
JPanel panel = new JPanel(new FlowLayout());
final JButton b = new JButton("Open File");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int ret = chooser.showDialog(b, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
// Don't know what you want to do
}
}
});
panel.add(b);
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("A", Integer.valueOf(10));
pieDataset.setValue("B", Integer.valueOf(20));
pieDataset.setValue("C", Integer.valueOf(30));
pieDataset.setValue("D", Integer.valueOf(10));
pieDataset.setValue("E", Integer.valueOf(20));
pieDataset.setValue("F", Integer.valueOf(10));
JFreeChart chart = ChartFactory.createPieChart("Pie Chart using JFreeChart", pieDataset, true, true, true);
JFrame frame1 = new JFrame();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChartPanel chartPanel = new ChartPanel(chart);
// chartPanel.setPreferredSize(new Dimension(600, 600));
frame1.getContentPane().add(chartPanel, BorderLayout.CENTER);
frame1.getContentPane().add(panel, BorderLayout.SOUTH);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
}
There is a class called ChartPanel. It is a sub class of JPanel class.
JPanel chartPanel = new ChartPanel(chart);
Then you can add this panel to the frame. hope this helps........
Replace this line
ChartFrame frame1=new ChartFrame("Pie Chart",chart);
with
panel.add(chart)
Kindly let me know the result

Categories