JFrame, trying to make button run another class - java

Pretty much what I'm trying to do is make a custom installer, I have buttons and that working fine but I want to run another class called CopyDir.java when I click on the button so that it copies the necessary files to the correct directory. Problem is, is that I'm a bit stumped on how to do this.
public class Frame extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton PC = new JButton("Install Mod (PC)");
JButton Steam = new JButton("Install Mod (Steam)");
JLabel Text = new JLabel("Welcome to the BTD 5 Mod Installer");
JLabel Text2 = new JLabel("Click on the button that matches your version of BTD 5");
JLabel Text3 = new JLabel("To install it for the version that you are using");
JLabel Text4 = new JLabel("© Nixxx60/Nanikos");
Frame() {
super("BTD 5 Mod Installer");
setBounds(100, 100, 400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(pane);
PC.setMnemonic('P');
PC.addActionListener(this);
pane.add(PC);
PC.requestFocus();
con.add(pane);
Steam.setMnemonic('P');
Steam.addActionListener(this);
pane.add(Steam);
Steam.requestFocus();
setVisible(true);
pane.add(Text);
pane.add(Text2);
pane.add(Text3);
pane.add(Text4);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == PC) {
JOptionPane.showMessageDialog(null, "Mod has been installed on PC/Cracked Edition!", "BTD 5 Installer",
JOptionPane.PLAIN_MESSAGE);
setVisible(true);
}
if (source == Steam) {
JOptionPane.showMessageDialog(null, "Mod has been installed for Steam Edition!", "BTD 5 Installer",
JOptionPane.PLAIN_MESSAGE);
setVisible(true);
}
}
public static void main(String args[]) {
new Frame();
}
}
Also, here is the code for the "CopyDir.java" Class.
package Nanikos.BTD5.Main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyDir {
public static void main(String args[]) throws Exception
{
copyFiles(new File("C:\\Users\\User\\Desktop\\BTD5 Mod Installer\\Mod Files\\PC Assets"),new File("C:\\Program Files (x86)\\Steam\\steamapps\\common\\BloonsTD5"));
System.out.println("Files Copied");
}
public static void copyFiles(File src,File des) throws Exception
{
if(src.isDirectory())
{
if(!des.exists()) des.mkdir();
String [] filePaths=src.list();
for(String filePath: filePaths)
{
File srcFile =new File(src, filePath);
File desFile =new File(des, filePath);
copyFiles(srcFile,desFile);
}
}
else
{
FileInputStream from =null;
FileOutputStream to =null;
from = new FileInputStream(src);
to = new FileOutputStream(des);
byte [] buffer=new byte[4096];
int byteReads;
while( (byteReads=from.read(buffer))!=-1 )
{
to.write(buffer,0,byteReads);
}
from.close();
to.close();
}
}
}

What you want is to launch your class as a Thread
To launch your class CopyDir as a thread, make it implement Thread, change your main method signature to this :
public void run() {
//Your code
}
Also, to pass parameters to your thread, add a constructor in your CopyDir class that takes the parameters you have and stores them as attributes, to be able to get it from your method.
Then, to launch the thread from your event listeners :
CopyDir myCopyThread = new CopyDir(inputPath,outputPath);
myCopyThread.start();
This code will create a thread that starts running CopyDir in the run() method

Related

java actionListener: retrieve TextField in a separate thread

i have a Frame which look like this:
public class Load_Frame extends JFrame implements ActionListener{
private JButton uploadButton, downloadButton;
private JTextField uploadField;
private String filename;
private Client client;
public Load_Frame(String username, Socket socket) {
this.client = new Client(username, socket);
uploadField = new JTextField ();
uploadField.setBounds(60,100,450,30);
uploadButton = new JButton ("Upload");
uploadButton.setBounds(410,150,100,30);
uploadButton.addActionListener(this);
downloadButton = new JButton ("Download");
downloadButton.setBounds(390,300,120,30);
downloadButton.addActionListener(this);
this.add(uploadField);
this.add(uploadButton);
this.add(downloadButton);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//Upload:
if (e.getSource()== uploadButton) {
this.filename = uploadField.getText();
File file = new File(filename);
client.upload(file);
}
//Download
else if (e.getSource()== downloadButton) {
filename = (String) filesList.getSelectedItem();
client.download(filename);
}
}
My problem is: i have been said that the frame and the "process" should be separated in different thread, so that when the process fail the frame don't freeze. So i need my Client to be a new thread.
But then, i still need acess to those "upload" and "download" button. I've read that i can easily do that like it:
public class Client implements Runnable, ActionListener{
...
public void actionPerformed(ActionEvent e){
if(e.getSource() == uploadButton){
File file = new File(filename); //how can i retrieve the filename??
upload(file);
}
}
and i'll just need to add another actionListener in my Frame class like that:
uploadButton.addActionListener(client);
(same for download of course)
My prolem is: how can i get the filename, the text written in the TextField of my Frame?? Should i give this TextField as a parameter for my client ? This will make the code look weird, and by weird i mean not very logical, so i hope there is another way to do so.
You can create two thread one for download and one for upload like below
public void actionPerformed(ActionEvent e){
if(e.getSource()==uploadButton){
new Thread(){
public void run(){
this.filename = uploadField.getText();
File file = new File(filename);
client.upload(file);
}
}.start();
}
else if(e.getSource() == downloadButton){
new Thread(){
public void run(){
this.filename = downloadField.getText();
File file = new File(filename);
client.download(file);
}
}.start();
}
}

Add a Java file in a Jpanel of another file

I have 2 Java files, the first one is the main java code behind the program. And second is a jfx.Webview. I've been trying for forever to include the jfx.Webview in a JPanel that I have on the first Java file. I'm new to Java, and it's definitely not as easy as i thought. Please, if someone with a better understanding could explain to me the proper way to get this done, that would be of great help.
Here are the 2 Java files after some cleaning up:
public class Xzibit07 {
public static void main(String[] args) {
generateUI();
}
private static void generateUI(){
XzibitUI program = new XzibitUI();
program.setVisible(true);
program.setTitle("Xzibit");
ImageIcon logoIcon = new ImageIcon(new ImageIcon("Data/Images/Logo.jpg").getImage().getScaledInstance(program.logoLabel.getWidth(), program.logoLabel.getHeight(), Image.SCALE_DEFAULT));
program.logoLabel.setIcon(logoIcon);
program.logoLabel.setBounds((program.logoPanel.getWidth()/2 - program.logoLabel.getWidth()/2), 0, 0, 0);
ImageIcon settingsIcon = new ImageIcon(new ImageIcon("Data/Images/Settings.png").getImage().getScaledInstance((program.logoPanel.getHeight()/4), (program.logoPanel.getHeight()/4), Image.SCALE_DEFAULT));
program.settingsLabel.setIcon(settingsIcon);
program.getContentPane().setBackground(Color.WHITE);
program.logoPanel.setBackground(Color.WHITE);
}
}
And the second:
public class XzibitWeb implements Runnable {
public String webPage = "http://www.example.com";
public static void main(String[] args) {
SwingUtilities.invokeLater(new XzibitWeb());
}
#Override
public void run() {
JFXPanel jfxPanel = new JFXPanel();
Platform.runLater(() -> {
WebView view = new WebView();
jfxPanel.setScene(new Scene(view, 1024, 400));
view.getEngine().load(webPage);
});
}
}
I think you are trying to do this
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm
From your code i think you are not adding the jfxPanel to the frame.

JTextArea.append not displaying

I'm trying to write the contents of an array to a JTextArea. I've tried everything I can think of, and I can't understand what isn't working here. I've stripped the unnecessary stuff out of my code, here's the two relevant classfiles:
Main class:
package irclogtest;
public class BriBotMain {
public static void main(String args[]) throws Exception {
boolean startup = true;
//frame test launch
BriDisplayGUI data = new BriDisplayGUI(startup);
data.irclog.append("BriBot Startup Successful!" + "\n");
//example access through function when startup is false (only in main class for sample code to demonstrate issue)
try {
BriDisplayGUI data2 = new BriDisplayGUI(false); //tells us which class we're accessing
String[] textForGUI = new String[2]; //tells us the array has 2 lines
textForGUI[0] = "this is the first line"; //set the first line of the array to this text
textForGUI[1] = "this is the second";
data2.arrayToDisplay(textForGUI); //appends contents of array to text window
}
catch(Exception e) {
System.out.println(e);
}
}
}
GUI display class:
package irclogtest;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
public class BriDisplayGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = -7811223081379421773L;
String file_name = "C:/Bribot/logfile.txt";
//these lines create the objects we use
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JButton pressme = new JButton("Click here");
JButton pressme2 = new JButton("Also here");
JTextArea irclog = new JTextArea( 20, 70);
JScrollPane scrollirc = new JScrollPane(irclog);
public BriDisplayGUI(boolean startup) { //startup function, opens and sets up the window
if(startup == true){
frame.setTitle("Bribot Test Frame"); frame.setBounds(100,100,840,420); //sets title of window, sets position and size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //tells program to end on window close
frame.add(pane); //adds the main display pane to the window
//panel customization goes here
pressme.addActionListener(this);
pane.add(pressme);
pressme2.addActionListener(this);
pane.add(pressme2);
pressme.requestFocusInWindow();
irclog.setEditable(false);
scrollirc.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
pane.add(scrollirc);
irclog.setLineWrap(true);
irclog.setWrapStyleWord(true);
//pane.add(inputthing);
frame.setVisible(true);
} else {
System.out.println("Display Class Called");
}
}
public void arrayToDisplay(String[] text) throws IOException {
int i;
for ( i=0; i < text.length; i++) {
irclog.append( text[i] + "\n");
System.out.println( i + ": " + text[i]);
}
}
public void singleToDisplay(String text) throws IOException {
irclog.append(text + "\n");
System.out.println(text);
}
//basic event handler
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == pressme) {
} else if(source == pressme2) {
}
}
}
The first append works fine, but the second doesn't, and I can't figure out why (although the for loop does, as the contents of the array get written to console). I've searched quite a bit and nothing I've tried works. Can anyone point out the inevitable obvious oversight here? I'm the definition of a novice, so any advice is appreciated.
Thanks!
The default constructor doesn't do anything, meaning it doesn't construct any kind of UI or display, what would be, an empty frame.
You seem to be thinking the text will appear in data when you are appending it to data1
Try calling this(false) within the default constructor
A better solution would be to construct the core UI from the default constructor and from the "startup" constructor call this() and then modify the UI in what ever way this constructor needs
It seems like you write a new program. Why do you use Swing? Did you take a look at JavaFX?
I am not sure if that is going to fix your problem but you could try a foreach
for(String s : text){
irclog.append(s+"\n");
}

how to use mouse click event

Hi i have a class where i am using mouseclick event i want to call another class when i click from my mouse
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
// System.out.println("Double-clicked on: " + o.toString());
String a=o.toString();
LiistSelection.setListIndex(a);
System.out.println(LiistSelection.getListIndex());
new MyGui4();
}
}
}
};
i want to call this class when user click on list then new window should open
here is my class mygui4.java
public class MyGui4 extends JFrame
{
JLabel jLabel1;
Container pane;
private static ResultSet resultSet = null;
public void Gui( )
{
{
getContentPane().setBackground(new java.awt.Color(255,153,51));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
Border border = LineBorder.createGrayLineBorder();
jLabel1 = new JLabel(image);
jLabel1.setBorder(border);
jLabel1.setBackground(Color.red);
c.add(jLabel1);
setLayout(null);
}
public static void main( String[] args )
{
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
}
}
You want to Create a object of another Class and call a function using a object.
class second
{
//.....
public void function()
{
//........
}
public void function(int index)
{
//..........
}
}
second s=new second();
s.function()//calling function
int i=10;
s.function(i)//calling function with parameter
Try This Example :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class m extends JFrame
{
String s="The Value of List is 10";
m()
{
setVisible(true);
pack();
setLayout(null);
JButton b=new JButton("Click to Open another form");
b.setBounds(10,10,200,40);
add(b);
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
new s(s);//calling another class contructor
}
});
}
public static void main (String[] args)
{
new m();
}
}
class s extends JFrame
{
s(String s)
{
setVisible(true);
setSize(100,100);
setTitle(s);
}
}
Click The button Another Class and Open The Window
It looks to me like you are tying to invoke the class MyGui4 from the command line when you start the JVM or from another application when you click on the JList, If so then the code needs to be the same in both places.
When invoked from the command line the main() method is invoked which in turn invokes 3 lines of code:
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
When you invoke the code when clicking on the JList you invoke 1 line of code:
new MyGui4();
Can you tell me what the difference is?
Of course I still don't understand the point of this code because none of the methods in your MyGui4 class accept a parameter. So it doesn't matter which item in the JList you click on you will still display the same GUI with the same information. You need to pass the selected object from your JList to your GUI.

JTabbedPane not switching tab contents

I'm having an issue with JTabbedPane, in that the contents of individual tabs aren't showing up (Every time I click a new tab, the active tab changes but the contents do not, so I see the same content no matter which tab is selected.).
I'm trying to write an IDE for my own programming language, but have never worked with JTabbedPane before. My tabbed pane consists of JEditTextArea's (user-written component) housed in JScrollPanes. Here is the responsible class
package tide.editor;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.syntax.jedit.*;
import org.syntax.jedit.tokenmarker.*;
#SuppressWarnings("serial")
public class Editor extends JFrame implements ActionListener {
//Version ID
final static String VERSION = "0.01a";
//The editor pane houses the JTabbedPane that allows for code editing
//JPanel editorPane;
JTabbedPane tabbedPanel;
//The JTextPanes hold the source for currently open programs
ArrayList<JEditTextArea> textPanes;
//The toolbar that allows for quick opening, saving, compiling etc
JToolBar toolBar;
//Buttons for the toolbar
JButton newButton, openButton, saveButton, compileButton, runButton;
public Editor()
{
super("tIDE v" + VERSION);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
init();
setVisible(true);
textPanes.get(0).requestFocus();
}
public void init()
{
//Initialise toolbar
toolBar = new JToolBar();
toolBar.setFloatable(false);
newButton = new JButton("New");
newButton.addActionListener(this);
openButton = new JButton("Open");
openButton.addActionListener(this);
saveButton = new JButton("Save");
saveButton.addActionListener(this);
compileButton = new JButton("Compile");
compileButton.addActionListener(this);
runButton = new JButton("Run");
runButton.addActionListener(this);
toolBar.add(newButton);
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(compileButton);
toolBar.add(runButton);
tabbedPanel = new JTabbedPane();
textPanes = new ArrayList<JEditTextArea>();
JEditTextArea initialProgram = createTextArea("program.t");
tabbedPanel.addTab(initialProgram.getName(), new JScrollPane(initialProgram));
getContentPane().add(tabbedPanel, BorderLayout.CENTER);
add(toolBar, BorderLayout.NORTH);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Editor();
}
});
}
JEditTextArea createTextArea(String name)
{
JEditTextArea editPane = new JEditTextArea(name);
editPane.setTokenMarker(new TTokenMarker());
textPanes.add(editPane);
return editPane;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newButton)
{
String filename = "program2";
boolean fileExists = true;
//Ensures that no duplicate files are created
while (fileExists)
{
fileExists = false;
//Get new file name from user
filename = JOptionPane.showInputDialog(null, "Enter a name for the file", "program.t");
//Cancel was clicked in the new file dialog
if (filename == null)
return;
for (JEditTextArea panes: textPanes)
{
if (panes.getName().equals(filename) || panes.getName().equals(filename.concat(".t")) || panes.getName().concat(".t").equals(filename))
fileExists = true;
}
}
//add extension if it is missing
if(!filename.endsWith(".t"))
filename = filename.concat(".t");
//Add the new "file" to the editor window in a new tab
tabbedPanel.addTab(filename, new JScrollPane(createTextArea(filename)));
tabbedPanel.setSelectedIndex(tabbedPanel.getSelectedIndex()+1);
}
if (e.getSource() == openButton)
{
File f = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose target file location");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"t source or bytecode(.t, .tbc)", "t", "tbc");
fileChooser.setFileFilter(filter);
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
f = fileChooser.getSelectedFile();
}
//Cancel button was clicked on the open file dialog
if (f == null)
return;
//Load the contents of the selected file into the editor
else
{
JEditTextArea textArea = null;
StringBuilder inputText = null;
try {
Scanner sc = new Scanner(f);
//Add a new text area to the editor
textArea = createTextArea(f.getName());
tabbedPanel.add(new JScrollPane(textArea), textArea.getName());
//The newly added tab is set as the active tab
tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
textArea.requestFocus();
inputText = new StringBuilder();
while (sc.hasNext())
{
inputText.append(sc.nextLine() + "\n");
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
//Set the contents of the current text area to that of the opened file
textArea.setText(inputText.toString());
}
}
}
}
1) remove code lines from FileIO related try - catch blok
textArea = createTextArea(f.getName());
tabbedPanel.add(new JScrollPane(textArea), textArea.getName());
//The newly added tab is set as the active tab
tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
textArea.requestFocus();
prepare those Object before of after Input / OutputStreams
2) close() all Objects from Input / OutputStreams, in the finally block (try - catch - finally)
3) JTextComponets implements read() and write(), accepting all separators, then there no reason programatically call for "\n"
4) use SwingWorker code for FileIO
This might not be solution for the root cause, but there might be some inconsistency in your code which is causing paint issues on the TestAreas, So I would suggest you to register a TabChageListener and then repaint the ScrollPane for that specific tab, this should work:
tabbedPanel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int selectedIndex = tabbedPane.getSelectedIndex();
// get the ScrollPane for this selectedIndex and then repaint it.
}
});
I've been struggling with this very problem for the last couple of hours.
In fact, it doesn't matter how many JEditTextArea you instantiate, they all rely on the same SyntaxDocument, thus the same text. That's just the way it's coded in JEditTextArea.
In constructor public JEditTextArea(TextAreaDefaults defaults) you will need to find the line:
setDocument(defaults.document);
and replace it with:
setDocument(new SyntaxDocument());
and it will instantiate a brand new Document every time you make a new JEditTextArea.

Categories

Resources