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");
}
}
});
}
}
Related
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.
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();
});
}
}
This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().
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..
i have created a Java program to save MAC Addresses to an external File. Below is the code:
import java.io.*;
public class MAC{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the MAC Addres : ");
File file = new File("mac.txt");
FileWriter fstream = new FileWriter("mac.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.newLine();
out.close();
}
}
I have also created a Swing Application. I am done with the Front End, but now I can't save MAC address to a external file using swing.
In my ActionListener, I am getting the values, but I have no idea how to save the details to a external file.
I am able to print the ActionListener values to the screen, but I want it to be saved in the external file.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.io.*;
public class TextForm extends JPanel {
private JTextField[] fields;
// Create a form with the specified labels, tooltips, and sizes.
public TextForm(String[] labels, int[] widths) {
super(new BorderLayout());
JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
add(labelPanel, BorderLayout.WEST);
add(fieldPanel, BorderLayout.CENTER);
fields = new JTextField[labels.length];
for (int i = 0; i < labels.length; i += 1) {
fields[i] = new JTextField();
if (i < widths.length)
fields[i].setColumns(widths[i]);
JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
lab.setLabelFor(fields[i]);
labelPanel.add(lab);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
p.add(fields[i]);
fieldPanel.add(p);
}
}
public String getText(int i) {
return (fields[i].getText());
}
public static void main(String[] args) {
String[] labels = { "Enter MAC Address : "};
int[] widths = { 17 };
final TextForm form = new TextForm(labels, widths);
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(form.getText(0));
}
});
JFrame f = new JFrame("Text Form Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(form, BorderLayout.NORTH);
JPanel p = new JPanel();
p.add(submit);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
Thank you.
Copy the working method into the actionPerformed method and swap.
out.write(in.readLine());
For:
out.write(form.getText(0));
Then wrap the lot of it in a try/catch.