Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm aspiring to be a software engineer, and I have been taking Computer Science courses for my degree college. While they teach us a lot of basics that are mostly easy to learn online, I also want to learn things such as common documentation conventions. I am sure that once I start taking courses like data structures they will teach a lot more about the processes leading up to the actually coding, which from what I understand are the most important parts. But I would like to start learning to do things properly early on, so I am trying to learn how to properly document my code.
I read the Wikipedia page about javadoc, and I tried to the best of my ability to replicate it. If anyone could provide any tips, pointers, or corrections to my documentation (or even the code) for this simple program I made just to practice documentation it would be much appreciated.
Transform.java
import javax.swing.JFrame;
/**
* #author Nekko Rivera nekkoriv#gmail.com
* #version 1.0
* #since 2015-08-9
*/
public class Transform
{
public static void main(String[] args)
{
Gui theGui = new Gui();
theGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theGui.setSize(600, 400);
theGui.setResizable(false);
theGui.setVisible(true);
}
}
Gui.java
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* #author Nekko Rivera nekkoriv#gmail.com
* #version 1.0
* #since 2015-08-9
*/
public class Gui extends JFrame
{
/**
* Generated by Eclipse
*/
private static final long serialVersionUID = 7253493887106168112L;
/**
* Name displayed on choiceBox for the user to select
*/
String[] portraitNames = {"Default", "Nurio", "Giada", "Triggah", "Spider"};
/**
* The images that will be displayed upon selection
*/
Icon[] portraits = {new ImageIcon(getClass().getResource("default.png")), new ImageIcon(getClass().getResource("nurio.png")), new ImageIcon(getClass().getResource("Giada.png")),
new ImageIcon(getClass().getResource("Triggah.png")), new ImageIcon(getClass().getResource("spider.png"))};
/**
* Allows the user to choose a portrait to display
*/
private JComboBox <String> choiceBox;
/**
* Prompt for the user to change their appearance
*/
private JLabel promptLabel;
/**
* Builds the window for the program
*/
/**
* Displays the image chosen by the user
*/
private JLabel pictureLabel;
public Gui()
{
super("Transform");
setLayout(new FlowLayout());
drawGui();
}
/**
* Draws the items onto the frame
*/
public void drawGui()
{
pictureLabel = new JLabel(portraits[0]);
promptLabel = new JLabel("Change appearance?");
choiceBox = new JComboBox <String> (portraitNames);
choiceBox.addItemListener(
new ItemListener(){
#Override
public void itemStateChanged(ItemEvent event)
{
if(event.getStateChange() == ItemEvent.SELECTED)
pictureLabel.setIcon(portraits[choiceBox.getSelectedIndex()]);
}
}
);
add(pictureLabel);
add(promptLabel);
add(choiceBox);
}
}
TLDR: is this documented correctly?
There is not really a correct way to do documentation. What is good documentation depends on a lot of factors:
the type of software (application, library, ...)
the target group of the documentation (fellow programmers, end users, ...)
conventions and tastes of your organisation/company
etc.
Javadoc only generates a specific kind of documentation, namely API documentation for programmer's using the documented things (this may include your future self). In light of this some general pointers can be given:
All classes, fields and methods visible from outside the package must be documented. This includes public classes and public and protected members (fields and methods). In your case, documentation for the public classes is missing.
Whether private and package private items must also be documented depends on local customs. It is never wrong to document something.
Useful Javadoc documentation for a method describes what a method does. It may also describe how the method does that, but in most cases that is not really interesting for the person using the method and can also be documented with non-Javadoc comments.
Documentation should be precise. If there are pre-conditions, they should be mentioned (for example, something cannot be null, a number must be >= 0, etc). If there are specific corner cases, they should be mentioned. If a method has side-effect, this must be mentioned.
I hope these pointers are helpful.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
Importer "kBrushless" states that is is not resolved of not a field. Any help?
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.drive.RobotDriveBase.MotorType;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
// import edu.wpi.first.hal.FRCNetComm.tResourceType;
// import edu.wpi.first.hal.HAL;
import frc.robot.autos.*;
import frc.robot.commands.*;
import frc.robot.subsystems.*;
public class Robot2 extends TimedRobot {
private static final int leadDeviceID = 1;
private static final int followDeviceID = 2;
private static final int kJoystickPort = 0;
private CANSparkMax m_leadMotor;
private CANSparkMax m_followMotor;
private Joystick m_joystick;
#Override
public void robotInit() {
m_leadMotor = new CANSparkMax(leadDeviceID, MotorType.kBrushless);
m_followMotor = new CANSparkMax(followDeviceID, MotorType.kBrushless);
m_leadMotor.restoreFactoryDefaults();
m_followMotor.restoreFactoryDefaults();
}
}
This is also using the WPI libraries and FRC. This is also using all of the imported libraries, as it is shown below.
You are importing the wrong MotorType enum:
the edu.wpi.first.wpilibj.drive.RobotDriveBase.MotorType doesn't contain a kBrushless constant.
it seems that you are using CANSparkMax (because you write m_leadMotor = new CANSparkMax(leadDeviceID, MotorType.kBrushless);)
the [CANSparkMax constructor](https://codedocs.revrobotics.com/java/com/revrobotics/cansparkmax#%3Cinit%3E(int,com.revrobotics.CANSparkMaxLowLevel.MotorType) takes as second parameter an instance of CANSparkMaxLowLevel.MotorType, which has a constant kBrushless
Therefore it seems that you should replace
import edu.wpi.first.wpilibj.drive.RobotDriveBase.MotorType;
with
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
and probably also add
import com.revrobotics.CANSparkMax;
Hello Guys I have my swing application running but I need to create an "initialization class" where I create instances with data to populate the program when I run it
If I create an instance with data in the MainJFrame constructor it's working perfectly but I need to populate the MainJFrame that will send it through all the panels from ANOTHER CLASS
Here is my MainJFrame Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UserInterface;
import Business.Initialization;
import Business.Inventory;
import Business.InventoryList;
import Business.Product;
import Business.ProductCatalog;
import Business.Store;
import Business.StoreDirectory;
import UserInterface.StarMarketAdmin.MarketAdminWorkArea;
import UserInterface.StoreAdmin.LoginStoreAdmin;
import java.awt.CardLayout;
import java.util.Collections;
import javax.swing.SwingUtilities;
public class MainJFrame extends javax.swing.JFrame {
/**
* Creates new form MainJFrame
*/
private StoreDirectory storeDirectory;
private InventoryList inventoryList;
private ProductCatalog productCatalog;
private Store store;
public MainJFrame() {
initComponents();
this.storeDirectory = new StoreDirectory();
this.inventoryList = new InventoryList();
this.productCatalog = new ProductCatalog();
this.store = new Store();
}
private void btnMarketAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MarketAdminWorkArea panel = new MarketAdminWorkArea(userProcessContainer,storeDirectory,inventoryList,productCatalog,store);
userProcessContainer.add("MarketAdminWorkArea", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
private void btnStoreAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LoginStoreAdmin panel = new LoginStoreAdmin(userProcessContainer,storeDirectory,inventoryList,productCatalog);
userProcessContainer.add("LoginStoreAdmin", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
}
Now if I create an instance like:
Store s = storeDirectory.addStore();
s.setStoreName("Eddie's Market");
s.setStreet("Plainfield Pike");
s.setCity("Johnston");
s.setState("RI");
s.setCountry("USA");
in the MainJFrame it's working 100% but I need to create it in another class and call it in the MainJFrame to send it from there to all the other pannels.
How can I do this ?
create public functions to acces the private class from outside
not sure what you want exactly, but the options are endless
like
public void initStore(){
}
or just get it
public Store getStore(){
retturn store;
}
or even create and return it from there:
public Store storeFactory(){
// code here
return store;
}
or if you want another store and return it
public Store storeFactory(){
// code here to create a new store
return store2;
}
* NOT ADVISED but also an option: static *
you can also create a static one, even make it public, however public access is not the nicest way. Better keep it private and work with function as above to get it. In normally would not advice static usage like this... but assuming the MainFrame is the main program... in this case there might be an exception on the not to use static ....
private static Store store;
or
public static Store store;
than you can access it from everywhere by:
MainJFrame.store
* end static remark *
but maybe you just meant this:
public putStore(Store store){
this.store=store;
}
so you can create it in other class, and get it from other classes
in the other class to create it you migth even first get it (init it in the mainFrame with null:
private Store store=null;
in the other class:
Store store = mainframe.getStore();
// code to create it
or only create it if not yet created:
if (store==null){
// Only create if still null
// code to create it here
}
// and here use it, just created or not
Migth be a weird and 'know it all' like advice, but:
all of the above is basic java knowledge about public, private, static and so on.... might look in to some tutorials, to understand the basic things.
Java can be a pain in the... in case you do not understand it (memory leaks and so on...) so please be sure you know what you do.... (in case you want to use it professionaly)
In java there is a big difference in declaring it, and initialising it:
this is a declaration:
private Store store:
this is the init:
store = // something, even putting it to null is an init
and the combination of declare and init:
private Store store=null;
the last one you need before you can call it from other classes, because you actually will not get the object, but a pointer tot the object.
To have a pointer, you need tot init it, than init to null is enough.... so there is at least a pointer.
Understanding the way of pointers and how things are passed in java, will save some memory issues in bigger programs.
Inject this Store instance into the MainJFrame constructor.
The Store class will hold the data and you can access it through get methods.
Have you thought about that?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to write a program that copies one file and copies it's contents to another. I have to have user chose the files. i am stuck can some one please help me.
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.swing.JFileChooser;
public class FileCopy {
public static void main(String[]Args) throws IOException {
JFileChooser chooser = new JFileChooser("/Users/josealvarado/Desktop/");
Path FROM = Paths.get(chooser);
Path TO = Paths.get(chooser);
//overwrite existing file, if exists
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
}
I only can guess, but i think you'll need a JFrame which will contain your JFileChooser, i made a small example without any functionality, only to show, how you could maybe reach your goal.
Please realize for your next question(s) here on SO, post what you tried and POST the errors / exception you get, otherwise it is hard to help or solve your problem!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.professional_webworkx.tutorial.jtable.view;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
/**
*
* #author ottp
*/
public class MainFrame extends JFrame {
private JFileChooser chooser;
public MainFrame() {
initGUI();
}
private void initGUI() {
chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(chooser.getSelectedFile().getName());
}
});
this.setTitle("FileChoosing and copy one file to another");
this.setSize(1024, 768);
this.getContentPane().add(chooser, BorderLayout.NORTH);
this.setVisible(true);
}
}
The Class to start your App
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.professional_webworkx.tutorial.jtable;
import de.professional_webworkx.tutorial.jtable.view.MainFrame;
import javax.swing.JFileChooser;
/**
*
* #author ottp
*/
public class JTableDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new MainFrame();
}
}
Hope this helps,
Patrick
Path FROM = Paths.get(chooser);
Path TO = Paths.get(chooser)
You can't pass a JFileChooser to Paths.get(). Here are the overloaded static methods
Paths.get(String first, String... more) - Converts a path string, or a sequence of strings that when joined form a path string, to a Path.
Paths.get(URI uri) - Converts the given URI to a Path object.
You're probably looking to pass a String. In order to to that, you need to get the String file path from the JFileChooser. To do that, you first need to chooser.showOpenDialog() which returns an int if the OK button is pressed after selecting a file (APPROVE_OPTION), So you want to do something like this
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
String path;
if (result == JFileChooser.APPROVE_OPTION) {
path = (chooser.getSelectedFile()).getAbsolutePath();
}
Then you can pass the path to Paths.get(path)
You should really have a look at How to Use File Choosers
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
* A simple panel for testing various parts of our game.
* This is not part of the game. It's just for testing.
*/
package game;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
* A simple panel for testing various parts of our game.
* This is not part of the game. It's just for testing.
*/
public class TestPanel extends JPanel
{
private static final long serialVersionUID = 1L; // Ignore this - It's just to get rid of a warning.
// Instance variable(s).
private Image backdrop;
/**
* Constructor - loads a background image
*/
public TestPanel ()
{
try
{
ClassLoader myLoader = this.getClass().getClassLoader();
InputStream imageStream = myLoader.getResourceAsStream("resources/path_1.jpg");
backdrop = ImageIO.read(imageStream);
// You will uncomment these lines when you need to read a text file.
InputStream pointStream = myLoader.getResourceAsStream("resources/ path_1.txt");
Scanner s = new Scanner (pointStream);
}
catch (IOException e)
{
System.out.println ("Could not load: " + e);
}
}
/**
* This paint meethod draws the background image anchored
* in the upper-left corner of the panel.
*/
public void paintComponent (Graphics g)
{
g.drawImage(backdrop, 0, 0, null);
}
/* Override the functions that report this panel's size
* to its enclosing container. */
public Dimension getMinimumSize()
{
return new Dimension (600, 600);
}
public Dimension getMaximumSize()
{
return getMinimumSize();
}
public Dimension getPreferredSize()
{
return getMinimumSize();
}
}
This code is aimed towards a videogame assignment I am working on for my Java course. This class is only used to test our code out. In the direction for the assignment, I was told to put code that is present within the try block, as show above. Apparently, the code should open a JPEG image that I have within a folder in my workspace. However, when I try the code, it only states:
Exception in thread "main" java.lang.NullPointerException at
java.io.Reader.<init>(Unknown Source) at
java.io.InputStreamReader.<init>(Unknown Source) at
java.util.Scanner.<init>(Unknown Source) at
game.TestPanel.<init>(TestPanel.java:43) at
game.TestApplication.main(TestApplication.java:24)
I am not fully clear on what inputStream and classLoaders do. So, if you have any basic information on either, that would be great. Also, I know the other methods below the constructor method have no code within them. The directions for my assignment have not stated what I should input into these methods.
enter code here
enter code here
You've got some extra spaces in the second filename there:
"resources/ path_1.txt"
Clearly that's a typo. Then, when you call getResourceAsStream with this stream, it doesn't find the file you want, because of those extra spaces, so that call returns a null pointer, which is being passed into scanner, and eventually causing the NPE.
There are lots of existing SO Questions that explain why getResourceAsStream returns null under various circumstances; e.g.
Junit + getResourceAsStream Returning Null
getResourceAsStream() is always returning null
getResourceAsStream returning null
The method getResourceAsStream returns null on ubuntu
They all boil down to one root cause: the class loader can't find the resource you told it to find. The javadoc says that if the classloader can't find the requested resource, it returns null rather than throwing an exception.
And that can happen for a variety of reasons. The common ones include:
the resource doesn't exist,
the resource is not on the classpath (e.g. it is a file in the file system),
it does exist on the classpath but you've used the wrong path string for it, or
you've used a relative path string, but the context you are resolving it is incorrect.
I have a panel where the user will search for a customer by entering a surname or ID. I want to implement some kind of table that displays each row of SQL query results. What's the best way to do this? The first thing that comes to my mind would be to use a multi-dimensional array and a JTextArea. What do you think?
Have you looked into a JTable?
Edit: This is my first time replying so I guess I'll notice when I do something wrong. I have recently created something similar to what you are aiming for, so this piece of code might set you on your way:
String[][] results = null;
if(query != null){
results = domeinController.Search(query);
} else {
results = domeinController.ReturnAllAccounts();
txtSearch.setText("");
}
TableModel table = new DefaultTableModel(results, new String[] {d("LBL_SERVICE"), d("LBL_ACC_NAME"), d("LBL_PASSWORD"), d("LBL_EMAIL")});
tblResults = new JTable(){
public boolean isCellEditable(int roxIndex, int colIndex){
return false;
}
};
jScrollPane1.setViewportView(tblResults);
tblResults.setModel(table);
tblResults.setAutoCreateRowSorter(true);
tblResults.setBounds(55, 145, 423, 228);
tblResults.getTableHeader().setAutoscrolls(true);
tblResults.getTableHeader().setReorderingAllowed(false);
tblResults.getTableHeader().setResizingAllowed(false);
tblResults.setShowVerticalLines(false);
tblResults.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
tblResultsMousePressed(evt);
}
});
Basically you create a tableModel with a 2D Array of data as your 1st parameter, and an array with headers for your 2nd parameter. After that you can specify behaviour to your table.
I highly recommend taking Glazed List into account.
It's a library which takes care of the most of the heavylifting related to presenting tabular data in a table with both filtering and sorting. It also provides a multithreading-safe datamodel. Using bare Swing and Java it's a lot lot harder to implement it all correctly.
Here is a nice tutorial provided. Once anybody starts writing CRUD GUIs, sooner or later all end up wanting so called "standard features" which all table oriented guis share in common. Why wasting time inventing it all and risking making a lot of mistakes, when you can build upon proven solutions. Especially, when it's so easy.
An example, displaying a XML based JTable:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
// a simple issues library
import ca.odell.issuezilla.*;
// glazed lists
import ca.odell.glazedlists.*;
import ca.odell.glazedlists.swing.*;
/**
* An IssueBrowser is a program for finding and viewing issues.
*
* #author <href="mailto:jesse#odel.on.ca">Jesse Wilson</a>
*/
public class IssuesBrowser {
/** event list that hosts the issues */
private EventList issuesEventList = new BasicEventList();
/**
* Create an IssueBrowser for the specified issues.
*/
public IssuesBrowser(Collection issues) {
issuesEventList.addAll(issues);
}
/**
* Display a frame for browsing issues.
*/
public void display() {
// create a panel with a table
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
EventListModel issuesListModel = new EventListModel(issuesEventList);
JList issuesJList = new JList(issuesListModel);
JScrollPane issuesListScrollPane = new JScrollPane(issuesJList);
panel.add(issuesListScrollPane, new GridBagConstraints(...));
// create a frame with that panel
JFrame frame = new JFrame("Issues");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(540, 380);
frame.getContentPane().add(panel);
frame.show();
}
/**
* Launch the IssuesBrowser from the commandline.
*/
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Usage: IssuesBrowser <file>");
return;
}
// load some issues
Collection issues = null;
try {
IssuezillaXMLParser parser = new IssuezillaXMLParser();
InputStream issuesInStream = new FileInputStream(args[0]);
issues = parser.loadIssues(issuesInStream, null);
issuesInStream.close();
} catch(IOException e) {
e.printStackTrace();
return;
}
// create the browser
IssuesBrowser browser = new IssuesBrowser(issues);
browser.display();
}
}