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.
Related
I hope everyone is doing well.
I'm trying to move the drop down arrow in a TitledPane to be laid out on the right, instead of the left like it is by default. I'm using JavaFX 8, and many of the resources I've found don't seem to work.
I have found that I am able to move the arrow a specific amount, like 20 pixels shown below
.accordion .title > .arrow-button .arrow
{
-fx-translate-x: 20;
}
But I want something responsive. Is there some way that I can get the width of the titled pane, and then subtract some pixels so that so that the arrow appears to be laid out on the right when resizing? Is there a better way to it? I added the element using SceneBuilder2 if that matters.
Thanks so much for your time.
Edit: The following was added for clarification
Primarily, I want the arrow to be right justified, like below
Instead of just "to the right" of the arrow. I really appreciate all the assistance.
Unfortunately, there's no public API for moving the arrow to the right side of the TitledPane. This doesn't mean this can't be accomplished, however, we just have to translate the arrow dynamically, using bindings. In order for the rest of the title area to look correct we'll also have to translate the text, and graphic if present, to the left. The easiest way to do all this is by subclassing TitledPaneSkin and accessing the internals of the "title region".
Here's an example implementation. It lets you position the arrow on the left or right side via CSS. It's also responsive to resizing as well as alignment and graphic changes.
package com.example;
import static javafx.css.StyleConverter.getEnumConverter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.css.CssMetaData;
import javafx.css.SimpleStyleableObjectProperty;
import javafx.css.StyleableObjectProperty;
import javafx.css.StyleableProperty;
import javafx.scene.Node;
import javafx.scene.control.Skin;
import javafx.scene.control.TitledPane;
import javafx.scene.control.skin.TitledPaneSkin;
import javafx.scene.layout.Region;
import javafx.scene.text.Text;
public class CustomTitledPaneSkin extends TitledPaneSkin {
public enum ArrowSide {
LEFT, RIGHT
}
/* ********************************************************
* *
* Properties *
* *
**********************************************************/
private final StyleableObjectProperty<ArrowSide> arrowSide
= new SimpleStyleableObjectProperty<>(StyleableProperties.ARROW_SIDE, this, "arrowSide", ArrowSide.LEFT) {
#Override protected void invalidated() {
adjustTitleLayout();
}
};
public final void setArrowSide(ArrowSide arrowSide) { this.arrowSide.set(arrowSide); }
public final ArrowSide getArrowSide() { return arrowSide.get(); }
public final ObjectProperty<ArrowSide> arrowSideProperty() { return arrowSide; }
/* ********************************************************
* *
* Instance Fields *
* *
**********************************************************/
private final Region title;
private final Region arrow;
private final Text text;
private DoubleBinding arrowTranslateBinding;
private DoubleBinding textGraphicTranslateBinding;
private Node graphic;
/* ********************************************************
* *
* Constructors *
* *
**********************************************************/
public CustomTitledPaneSkin(TitledPane control) {
super(control);
title = (Region) Objects.requireNonNull(control.lookup(".title"));
arrow = (Region) Objects.requireNonNull(title.lookup(".arrow-button"));
text = (Text) Objects.requireNonNull(title.lookup(".text"));
registerChangeListener(control.graphicProperty(), ov -> adjustTitleLayout());
}
/* ********************************************************
* *
* Skin Stuff *
* *
**********************************************************/
private void adjustTitleLayout() {
clearBindings();
if (getArrowSide() != ArrowSide.RIGHT) {
// if arrow is on the left we don't need to translate anything
return;
}
arrowTranslateBinding = Bindings.createDoubleBinding(() -> {
double rightInset = title.getPadding().getRight();
return title.getWidth() - arrow.getLayoutX() - arrow.getWidth() - rightInset;
}, title.paddingProperty(), title.widthProperty(), arrow.widthProperty(), arrow.layoutXProperty());
arrow.translateXProperty().bind(arrowTranslateBinding);
textGraphicTranslateBinding = Bindings.createDoubleBinding(() -> {
switch (getSkinnable().getAlignment()) {
case TOP_CENTER:
case CENTER:
case BOTTOM_CENTER:
case BASELINE_CENTER:
return 0.0;
default:
return -(arrow.getWidth());
}
}, getSkinnable().alignmentProperty(), arrow.widthProperty());
text.translateXProperty().bind(textGraphicTranslateBinding);
graphic = getSkinnable().getGraphic();
if (graphic != null) {
graphic.translateXProperty().bind(textGraphicTranslateBinding);
}
}
private void clearBindings() {
if (arrowTranslateBinding != null) {
arrow.translateXProperty().unbind();
arrow.setTranslateX(0);
arrowTranslateBinding.dispose();
arrowTranslateBinding = null;
}
if (textGraphicTranslateBinding != null) {
text.translateXProperty().unbind();
text.setTranslateX(0);
if (graphic != null) {
graphic.translateXProperty().unbind();
graphic.setTranslateX(0);
graphic = null;
}
textGraphicTranslateBinding.dispose();
textGraphicTranslateBinding = null;
}
}
#Override
public void dispose() {
clearBindings();
unregisterChangeListeners(getSkinnable().graphicProperty());
super.dispose();
}
/* ********************************************************
* *
* Stylesheet Handling *
* *
**********************************************************/
public static List<CssMetaData<?, ?>> getClassCssMetaData() {
return StyleableProperties.CSS_META_DATA;
}
#Override
public List<CssMetaData<?, ?>> getCssMetaData() {
return getClassCssMetaData();
}
private static class StyleableProperties {
private static final CssMetaData<TitledPane, ArrowSide> ARROW_SIDE
= new CssMetaData<>("-fx-arrow-side", getEnumConverter(ArrowSide.class), ArrowSide.LEFT) {
#Override
public boolean isSettable(TitledPane styleable) {
Property<?> prop = (Property<?>) getStyleableProperty(styleable);
return prop != null && !prop.isBound();
}
#Override
public StyleableProperty<ArrowSide> getStyleableProperty(TitledPane styleable) {
Skin<?> skin = styleable.getSkin();
if (skin instanceof CustomTitledPaneSkin) {
return ((CustomTitledPaneSkin) skin).arrowSide;
}
return null;
}
};
private static final List<CssMetaData<?, ?>> CSS_META_DATA;
static {
List<CssMetaData<?,?>> list = new ArrayList<>(TitledPane.getClassCssMetaData().size() + 1);
list.addAll(TitledPaneSkin.getClassCssMetaData());
list.add(ARROW_SIDE);
CSS_META_DATA = Collections.unmodifiableList(list);
}
}
}
You can then apply this skin to all TitledPanes in your application from CSS, like so:
.titled-pane {
-fx-skin: "com.example.CustomTitledPaneSkin";
-fx-arrow-side: right;
}
/*
* The arrow button has some right padding that's added
* by "modena.css". This simply puts the padding on the
* left since the arrow is positioned on the right.
*/
.titled-pane > .title > .arrow-button {
-fx-padding: 0.0em 0.0em 0.0em 0.583em;
}
Or you could target only certain TitledPanes by adding a style class and using said class instead of .titled-pane.
The above works with JavaFX 11 and likely JavaFX 10 and 9 as well. To get it to compile on JavaFX 8 you need to change some things:
Import com.sun.javafx.scene.control.skin.TitledPaneSkin instead.
The skin classes were made public in JavaFX 9.
Remove the calls to registerChangeListener(...) and unregisterChangeListeners(...). I believe replacing them with the following is correct:
#Override
protected void handleControlPropertyChange(String p) {
super.handleControlPropertyChange(p);
if ("GRAPHIC".equals(p)) {
adjustTitleLayout();
}
}
Use new SimpleStyleableObjectProperty<ArrowSide>(...) {...} and new CssMetaData<TitledPane, ArrowSide>(...) {...}.
Type inference was improved in later versions of Java.
Use (StyleConverter<?, ArrowSide>) getEnumConverter(ArrowSide.class).
There was a bug in the generic signature of getEnumConverter that was fixed in a later version. Using the cast works around the problem. You may wish to #SuppressWarnings("unchecked") the cast.
Issue: Even with the above changes there's a problem in JavaFX 8—the arrow is only translated once the TitledPane is focused. This doesn't appear to be a problem with the above code as even changing the alignment property does not cause the TitledPane to update until it has focus (even when not using the above skin, but rather just the default skin). I've been unable to find a workaround to this problem (while using the custom skin) but maybe you or someone else can. I was using Java 1.8.0_202 when testing for JavaFX 8.
If you don't want to use a custom skin, or you're on JavaFX 8 (this will cause the arrow to be translated without needing to focus the TitledPane first), you can extract the necessary code, with some modifications, into a utility method:
public static void putArrowOnRight(TitledPane pane) {
Region title = (Region) pane.lookup(".title");
Region arrow = (Region) title.lookup(".arrow-button");
Text text = (Text) title.lookup(".text");
arrow.translateXProperty().bind(Bindings.createDoubleBinding(() -> {
double rightInset = title.getPadding().getRight();
return title.getWidth() - arrow.getLayoutX() - arrow.getWidth() - rightInset;
}, title.paddingProperty(), title.widthProperty(), arrow.widthProperty(), arrow.layoutXProperty()));
arrow.setStyle("-fx-padding: 0.0em 0.0em 0.0em 0.583em;");
DoubleBinding textGraphicBinding = Bindings.createDoubleBinding(() -> {
switch (pane.getAlignment()) {
case TOP_CENTER:
case CENTER:
case BOTTOM_CENTER:
case BASELINE_CENTER:
return 0.0;
default:
return -(arrow.getWidth());
}
}, arrow.widthProperty(), pane.alignmentProperty());
text.translateXProperty().bind(textGraphicBinding);
pane.graphicProperty().addListener((observable, oldGraphic, newGraphic) -> {
if (oldGraphic != null) {
oldGraphic.translateXProperty().unbind();
oldGraphic.setTranslateX(0);
}
if (newGraphic != null) {
newGraphic.translateXProperty().bind(textGraphicBinding);
}
});
if (pane.getGraphic() != null) {
pane.getGraphic().translateXProperty().bind(textGraphicBinding);
}
}
Note: While this puts the arrow on the right without having to focus the TitledPane first, the TitledPane still suffers from the issue noted above. For instance, changing the alignment property doesn't update the TitledPane until it's focused. I'm guessing this is simply a bug in JavaFX 8.
This way of doing things is not as "easy" as the skin approach and requires two things:
The TitledPane must be using the default TitledPaneSkin.
The TitledPane must have been displayed in a Window (window was showing) before calling the utility method.
Due to the lazy nature of JavaFX controls, the skin and the associated nodes will not have been created until the control has been displayed in a window. Calling the utility method before the control was displayed will result in a NullPointerException being thrown since the lookup calls will return null.
If using FXML, note that the initialize method is called during a call to FXMLLoader.load (any of the overloads). This means, under normal circumstances, it's not possible for the created nodes to be part of a Scene yet, let alone a showing Window. You must wait for the TitledPane to be displayed first, then call the utility method.
Waiting for the TitledPane to be displayed can be achieved by listening to the Node.scene property, the Scene.window property, and the Window.showing property (or you could listen for WindowEvent.WINDOW_SHOWN events). However, if you immediately put the loaded nodes into a showing Window, then you can forgo observing the properties; call the utility method inside a Platform.runLater call from inside initialize.
When using the skin approach, the whole wait-for-showing-window hassle is avoided.
Usual Warning: This answer relies on the internal structure of TitledPane which may change in a future release. Be cautious when changing JavaFX versions. I only (somewhat) tested this on JavaFX 8u202 and JavaFX 11.0.2.
This isn’t exactly the same, visually, but you can hide the arrow button and create a graphic that acts like an arrow button. TitledPane extends Labeled, so you have control over the placement of the graphic relative to the text, via the contentDisplay property.
First, hide the arrow button in the stylesheet:
.accordion .title > .arrow-button
{
visibility: hidden;
}
In the code, you can create a Label to act as a fake button and set it as the TitledPane’s graphic. The entire title line is sensitive to the mouse, so an interactive control (like a Button) is not needed.
Label collapseButton = new Label();
collapseButton.textProperty().bind(
Bindings.when(titledPane.expandedProperty())
.then("\u25bc").otherwise("\u25b6"));
titledPane.setGraphic(collapseButton);
titledPane.setContentDisplay(ContentDisplay.RIGHT);
In FXML you can just add nodeOrientation="RIGHT_TO_LEFT"
or use yourNode.setNodeOrientation((NodeOrientation orientation)
https://openjfx.io/javadoc/11/javafx.graphics/javafx/scene/Node.html#setNodeOrientation(javafx.geometry.NodeOrientation)
I cannot figure out why the following command does not work when the program calls the command. I dont have a very good background in Java, but as I understand it, the command should execute the print line statement when i press the button on the joystick that calls the command. Im not sure whether the problem may be that the command needs a Action listener or button listener somewhere, or whether I need to somehow relate the command to the same console. There should only be one recognized console it can print to, which i know works from other print line statements in the original program... right?
Here is the library which may help
THE PROGRAM:
/*--------------------------------------------------------------------------
--*/
/* 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 org.usfirst.frc.team5621.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
private DifferentialDrive m_robotDrive
= new DifferentialDrive(new Spark(0), new Spark(1));
static Joystick m_stick = new Joystick(1);
private Timer m_timer = new Timer();
static Subsystem ExampleSubsystem;
Command ExampleCommand;
Command CompressCommand;
Command DecompressCommand;
Command OpenClawCommand;
Command CloseClawCommand;
Command CompressorToggleCommand;
public static class OI {
//Create Joystick and Buttons
static Joystick m_stick = new Joystick(1);
static Button button1 = new JoystickButton(m_stick, 1);
static Button button2 = new JoystickButton(m_stick, 2);
static Button button3 = new JoystickButton(m_stick, 3);
static Button button4 = new JoystickButton(m_stick, 4);
static Button button5 = new JoystickButton(m_stick, 5);
static Button button6 = new JoystickButton(m_stick, 6);
static Button button7 = new JoystickButton(m_stick, 7);
static Button button8 = new JoystickButton(m_stick, 8);
public OI() {
// Define Commands for Joystick Buttons
OI.button1.whileHeld(new CompressorToggleCommand());
OI.button2.whileHeld(new CompressCommand());
OI.button3.whileHeld(new DecompressCommand());
OI.button4.whileHeld(new OpenClawCommand());
OI.button5.whileHeld(new CloseClawCommand());
OI.button6.whileHeld(new ExampleCommand());
OI.button7.whileHeld(new ExampleCommand());
OI.button8.whileHeld(new ExampleCommand());
}
}
public class Compressor {
Compressor c = new Compressor();
}
public class Solenoid {
Solenoid exampleSolenoid = new Solenoid();
}
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
#Override
public void robotInit() {
}
/**
* This function is run once each time the robot enters autonomous mode.
*/
#Override
public void autonomousInit() {
m_timer.reset();
m_timer.start();
}
/**
* This function is called periodically during autonomous.
*/
#Override
public void autonomousPeriodic() {
// Drive for 2 seconds
if (m_timer.get() < 2.0) {
m_robotDrive.arcadeDrive(0.5, 0.0); // drive forwards half speed
} else {
m_robotDrive.stopMotor(); // stop robot
}
}
/**
* This function is called once each time the robot enters teleoperated mode.
*/
#Override
public void teleopInit() {
System.out.println("TeleOperated Mode Enabled");
}
/**
* This function is called periodically during teleoperated mode.
*/
#Override
public void teleopPeriodic() {
m_robotDrive.arcadeDrive(m_stick.getY(), m_stick.getX());
}
/**
* This function is called periodically during test mode.
*/
#Override
public void testPeriodic() {
}
}
THE COMMAND
/*----------------------------------------------------------------------------*/
/* 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 org.usfirst.frc.team5621.robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* An example command. You can replace me with your own command.
*/
public class CompressCommand extends Command {
public CompressCommand() {
}
// Called just before this Command runs the first time
#Override
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
#Override
protected void execute() {
System.out.println("Compressing...");
exampleSolenoid.set(true);
}
// Make this return true when this Command no longer needs to run execute()
#Override
protected boolean isFinished() {
return false;
}
}
First off, I'd like to say that it's nice to see a fellow FRC programmer on Stack Overflow. Pertaining to your question, your problem may lie in the fact that you are declaring multiple public classes in the same file. This is very bad practice in Java programming. The problem you are looking to solve is here:
public OI() {
// Define Commands for Joystick Buttons
OI.button1.whileHeld(new CompressorToggleCommand());
OI.button2.whileHeld(new CompressCommand());
OI.button3.whileHeld(new DecompressCommand());
OI.button4.whileHeld(new OpenClawCommand());
OI.button5.whileHeld(new CloseClawCommand());
OI.button6.whileHeld(new ExampleCommand());
OI.button7.whileHeld(new ExampleCommand());
OI.button8.whileHeld(new ExampleCommand());
}
Once again, it is bad practice to have nested public classes, but what is really causing your problem is that you set the Button-On-Press actions for each button in the constructor of your OI class, but you never actually make an OI object, therefore the constructor is never called, and the code is never run. In your robotInit function, make an new OI object:
void robotInit() {
OI myOI = new OI();
}
Also remove the OI tag from your statements inside of the OI class. It is not needed. So that this:
OI.button1.whileHeld(new CompressorToggleCommand());
Becomes this:
button1.whileHeld(new CompressorToggleCommand());
I would also recommend moving all of your object initializations to robotInit. I would suggest making all of your many nested classes each in their own file, and be sure to make objects of all of these classes in your main Robot class. I would also suggest reading up on some basic Object Oriented Programming concepts such as how constructors work, as well as how to use classes and objects in Java. Also maybe read up on the FRC functions you are using in the FRC API Reference
I have a Java Application, I am wanting to format a button as either Active or Inactive (Also possibly a hover method).
The code as I would like to implement it:
//Home Tab - Active by default
home = new TabButton();
home.setSize(new Dimension(tabWidth, tabHeight));
home.setFont(getLauncherFont(34));
home.setForeground(Color.white);
home.setText("HOME");
home.setBounds(160, 0, tabWidth, tabHeight);
home.setActive(); --> This Method is what I would like to create
I already have a class to create a JButton for the tab:
package com.anarcist.minemodloaderv1.skin.components;
import java.awt.Color;
import javax.swing.JButton;
/**
*
* #author anarcist
*/
public class TabButton extends JButton {
public TabButton() {
this.setBorderPainted(false);
this.setFocusPainted(false);
this.setContentAreaFilled(true);
this.setBackground(Color.blue);
}
}
I have researched abstract classes. But my TabButton class already extends JButton.
I would like a method like this:
public void setActive(){
this.setBackground(Color.red);
//Any other changes a want to make regularly
}
That can simply be implemented like this home.setActive();
My Question I suppose is: Is it easy enough to implement what I am looking for, or will I have to got the long way and set all attributes manually every time?
What you've described in the post can be done like this:
package com.anarcist.minemodloaderv1.skin.components;
import java.awt.Color;
import javax.swing.JButton;
/**
*
* #author anarcist
*/
public class TabButton extends JButton {
public TabButton() {// initialize
this.setBorderPainted(false);
this.setFocusPainted(false);
this.setContentAreaFilled(true);
this.setBackground(Color.blue);
}
// add your own methods or override JButton methods
public void setActive(){
//Add code
//example: setEnabled(true);
}
}
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);
}
}
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