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
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;
I have a program that will not compile due to certain libraries not being found. I have tried using the -cp %pathTo\lib%/* command to include all .jar files. That gets it to compile but then when I try to run the program it tells me it cannot find or load the main class.
So I want to manually include each .jar file, my only problem is I don't know which exact ones to include.
/* ---------------------
* ThermometerDemo1.java
* ---------------------
* (C) Copyright 2002-2007, by Object Refinery Limited.
*
*/
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.data.general.ValueDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
/**
* A simple demonstration application showing how to create a thermometer.
*/
public class ThermDemo extends ApplicationFrame {
static class ContentPanel extends JPanel implements ChangeListener {
JSlider slider;
DefaultValueDataset dataset;
/**
* Default constructor.
*/
public ContentPanel() {
super(new BorderLayout());
this.slider = new JSlider(0, 100, 50);
this.slider.setPaintLabels(true);
this.slider.setPaintTicks(true);
this.slider.setMajorTickSpacing(25);
this.slider.addChangeListener(this);
add(this.slider, BorderLayout.SOUTH);
this.dataset = new DefaultValueDataset(this.slider.getValue());
add(new ChartPanel(createChart(this.dataset)));
}
private static JFreeChart createChart(ValueDataset dataset) {
ThermometerPlot plot = new ThermometerPlot(dataset);
JFreeChart chart = new JFreeChart(
"Thermometer Demo 1", // chart title
JFreeChart.DEFAULT_TITLE_FONT,
plot, // plot
true // no legend
);
plot.setInsets(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setPadding(new RectangleInsets(10.0, 10.0, 10.0, 10.0));
plot.setThermometerStroke(new BasicStroke(2.0f));
plot.setThermometerPaint(Color.lightGray);
plot.setUnits(ThermometerPlot.UNITS_FAHRENHEIT);
plot.setGap(3);
return chart;
}
public void stateChanged(ChangeEvent e) {
this.dataset.setValue(new Integer(this.slider.getValue()));
}
}
/**
* Creates a new demo.
*
* #param title the frame title.
*/
public ThermDemo(String title) {
super(title);
JPanel chartPanel = createDemoPanel();
setContentPane(chartPanel);
}
/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* #return A panel.
*/
public static JPanel createDemoPanel() {
return new ContentPanel();
}
/**
* Starting point for the demonstration application.
*
* #param args ignored.
*/
public static void main(String[] args) {
ThermDemo demo = new ThermDemo("Thermometer Demo 1");
demo.pack();
demo.setVisible(true);
}
}
Commands:
to compile:
javac -cp B:\Programming\Java\Compiler\lib* ThermDemo.java
to run: java ThermDemo
After compiling there are two new files in my current directory.
ThermDemo$ContentPanel.class, and ThermDemo.class
to compile: javac -cp B:\Programming\Java\Compiler\lib* ThermDemo.java
to run: java ThermDemo
Change that to:
java -cp .;B:\Programming\Java\Compiler\lib* ThermDemo
The runtime classpath needs to include (at least) all of the compile-time dependencies. The ".;" is needed to tell java to look in the current directory as well ... to find the ".class" files you just compiled.
Actually, this solution only applies to your current problem. There is a lot of complexity in the way that classpaths work, and you would be advised to spend time reading up on it. Here's a good place to start:
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
https://docs.oracle.com/javase/tutorial/essential/environment/paths.html
(I'm assuming that ThermoDemo.java has a main method with the appropriate signature.)
ThermDemo.class is the class that you have to run. ThermDemo$ContentPanel.class is the inner class. When you compile a class having inner classes, both class files will be generated.
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.
am having a problem trying to access this keyword in a different class using Java programming. I have tried Context, class.this but no help yet...
I have created a project using NetBeans gui builder, I want when i click button the form to get disposed...
Main class contains the click event for disposing the JFrame Form
BestQSystems.java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CloseWindow.closeWindow();
}
Class to close the JFrame: CloseWindow.java
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import javax.naming.Context;
/*
* 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.
*/
/**
*
* #author Benson
*/
public class CloseWindow {
public static void closeWindow(){
WindowEvent widnowEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(widnowEvent);
}
}
Am having an error in this line WindowEvent widnowEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING); Please advise me on how to access this keyword in a different class.
You can pass a reference to this to the other method. For example:
BestQSystems.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
CloseWindow.closeWindow(this);
}
and in the CloseWindow.java
public class CloseWindow {
public static void closeWindow(BestQSystems ref){
WindowEvent widnowEvent = new WindowEvent(ref, WindowEvent.WINDOW_CLOSING);
}
}
I'm writing an eclipse plugin for a domain specific language. I've subclassed editor and things are working fine.
I'd like to add a popup menu so that I can do my own refactorings. I've used org.eclipse.ui.popupmenus to add the popupmenu, which when you right click on the editor, does provide the menu, it can be clicked, and the click executes the following method:
public void run(IAction action) {
MessageDialog.openInformation(shell, "SyntaxColoringCSharp", "refactorA was executed.");
}
My problem is that I don't know where in the editor the click happened - so it's difficult for me to get the right bit of the file to perform the refactoring on. The cursor doesn't move to where the click happened.
How do I find out where in the editor the popupmenu click happened? (i.e. how do the Java refactoring get this information?)
Here is the basic class I'm working with:
package arteditor.popup.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.editors.text.TextEditor;
import editoractions.EditorActions;
public class refactorA implements IObjectActionDelegate {
private Shell shell;
/**
* Constructor for Action1.
*/
public refactorA() {
super();
}
/**
* #see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
shell = targetPart.getSite().getShell();
}
/**
* #see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
MessageDialog.openInformation(shell, "SyntaxColoringCSharp", "refactorA was executed.");
}
/**
* #see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
}
It is normal to use the cursor (caret) position for the right click action - that is what the Java refactoring does in the Java editor context menu.
The StyledText widget has various methods to return the caret position.