I'm re-programming one of my old login screen codes and I am changing the:
JPasswordField.getText();
To:
JPasswordFieald.getPassword();
Which is a lot harder because it outputs charecters.
Anyway, JFrame.dispose() isnt working for me. I want my program to dispose an old JFrame to a new JFrame (e.e JFrame2).
Here is my code:
public class Launcher {
//Define Variables
public static String VER = "1.1.0";
public static String STATE = " ALPHA ";
public static JFrame launcher;
public static char[] sPass;
public static String sUser;
//Create widgets
public static JTextField User = new JTextField();
public static JPasswordField Pass = new JPasswordField();
public static JButton Login = new JButton("Login");
//Runs when program starts
public static void main(String[] args) {
NewFrame("Infinite Doom Launcher");
//Checks if login has been pressed
Login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
sUser = User.getText();
sPass = Pass.getPassword();
//checks if password is correct
if(CheckPass(sPass)) {
if(sUser.equals("genfy")){
Game.main(null);
launcher.dispose();
}
}
}
});
}
//Creates new frame
public static void NewFrame(String Name) {
JFrame launcher = new JFrame(Name + " " + STATE + VER);
launcher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
launcher.setSize(500,95);
launcher.setResizable(false);
//Add widgets to a Border Layout
launcher.setLayout(new BorderLayout());
launcher.add(User, BorderLayout.NORTH);
launcher.add(Pass, BorderLayout.CENTER);
launcher.add(Login, BorderLayout.SOUTH);
//Set visible
launcher.setVisible(true);
}
//Checks if the entered password is correct
private static boolean CheckPass(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'g', 'e', 'n', 'f', 'y', 'g', 'e', 'n', 'y', 's' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
}
So the problem seems to be occurring at:
//checks if password is correct
if(CheckPass(sPass)) {
if(sUser.equals("genfy")){
Game.main(null);
launcher.dispose();
}
specifically:
launcher.dispose();
So when I press JButton(login) this error appears:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Launcher$1.actionPerformed(Launcher.java:42)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I apologize for my code being so long.
It seems there is a scope problem in NewFrame method at this line:
JFrame launcher = new JFrame(Name + " " + STATE + VER);
This launcher variable is local to NewFrame method and is hidding launcher class member. So when you call launcher.dispose() within actionPerformed() method you get a NullPointerException. To solve this you should do this change:
launcher = new JFrame(Name + " " + STATE + VER);
And also take a look to this topic: The Use of Multiple JFrames, Good/Bad Practice?
Off-topic
As #kleopatra has suggested, learn about java naming conventions and stick to them. See more in this document: Java Code Conventions
Related
I have problems with idS. in sellContainer idS is 1 and in sellCtr is always 0 so the method addItemToSell is not working. Always give null pointer exception.
public class SellCtr{
private SellContainer sellContainer;
private OrderLineSell ols;
private int idS;
private int idOls;
public SellCtr(){
sellContainer = SellContainer.getInstance();
}
public void createSell(String date, Customer c, Employee e){
Sell sell = new Sell(date,c,e);
sellContainer.addSell(sell);
idS = sell.getId();
}
public void addItemToSell(OrderLineSell orderLineSell){
sellContainer.findSell(idS).addOrderLineSell(orderLineSell);
}
public int getId(){
return idS;
}
public int getIdOls(){
return idOls;
}
public Sell findSell(int idS){
return sellContainer.findSell(idS);
}
}
and the other class is :
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
public void addSell(Sell s){
idS++;
s.setId(idS);
sales.add(s);
}
public Sell findSell(int idS){
for(Sell sell : sales){
if(sell.getId()==idS){
return sell;
}
}
return null;
}
}
This is the error :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at controlLayer.SellCtr.addItemToSell(SellCtr.java:24)
at tuiLayer.SaleAddItemToSaleGUI$2.actionPerformed(SaleAddItemToSaleGUI.java:93)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I have rebuild the project and the exceptions changed.
EDIT 3 : I have made idS static and now it works. Thanks a lot guys!
I suggest you
make sure you are compiling all your classes. A build tool like maven or gradle will help.
you use enum for singletons. These are thread safe and simpler.
disable the feature in eclipse which allows you to run code which doesn't compile. This only delays finding errors which makes them worse.
I would replace
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
with
public enum SellContainer {
INSTANCE;
private final List<Sell> sales = new ArrayList<>();
private int idS = 0;
Initiate the object before the return object is back to the called method.
In SellContainer, if condition failure leads to give back the Sell Object as NULL.
You need to modify this logic.
return null;
So I am trying to make a simple chat client but somehow the connection doesn't work. Can you help me? This is what i wrote:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class game implements ActionListener{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String [] args){
game g = new game();
g.go();
}public void go(){
JFrame frame = new JFrame("Chat");
JButton sendB = new JButton("Send");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane s = new JScrollPane(incoming);
s.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
s.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(25);
sendB.addActionListener(this);
mainPanel.add(s);
mainPanel.add(outgoing);
mainPanel.add(sendB);
setUpnetworking();
Thread readerThread = new Thread( new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setVisible(true);
frame.setSize(800,500);
frame.setResizable(false);
}public void actionPerformed(ActionEvent e){
try{
writer.println(outgoing.getText());
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}public void setUpnetworking(){
try {
sock = new Socket("127.0.0.1", 5000 );
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
} catch (IOException exx) {
exx.printStackTrace();
}
}public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while ((message = reader.readLine()) != null){
System.out.println("read" + message);
incoming.append(message + "\n");
}
}catch (Exception exx){exx.printStackTrace();}
}
}
}
errors i got when i ran it:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at game.setUpnetworking(game.java:66)
at game.go(game.java:45)
at game.main(game.java:18)
java.lang.NullPointerException
at game$IncomingReader.run(game.java:79)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at game.actionPerformed(game.java:57)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
i really don't know what's the problem :( can someone help me so i can build a working Chat Client? I use Eclipse.
Sorry for bad Englisch, I am from The Netherlands
For a chat app you need both backend and client-side solutions.
To skip the part with server-side solution development you can use a ready backend and SDK provided by some platforms. That should save you a lot of time and effort and you will be able to concentrate on UI implementation.
Here are some providers you might consider using:
ConnectyCube
Firebase
Sendbird
Layer
Here is also an article comparing features provided by some of them.
You really need to build a server. You would need to go through networking a bit. But just in case you need a server, I made one few months back. Run it separately. See if you can make it work.
https://github.com/DhavalKapil/ForwardingServer
I've been searching through my code for hours now, and just can't figure out where this exception occurs.
The program is based on an implemented node list.
Code:
Objectlist class:
public class Billiste{
// Datafelter
private Bil forsteBil;
public Billiste(){
forsteBil = null;
}
public void settInnNyBil(Bil y){
/*if(ny == null){
return;
}*/
System.out.println("fjdklsadkjfldsk");
if(forsteBil == null){
forsteBil = y;
}
else{
Bil løper = forsteBil;
while(løper.nesteBil != null){
løper = løper.nesteBil;
}
løper.nesteBil = y;
}
System.out.println(y);
}
// Metadata om listeobjektene
public String toString() {
String resultat = "";
Bil løper = forsteBil;
while(løper!=null){
resultat += løper.toString() + "\n";
løper = løper.nesteBil;
}
if(!resultat.equals("")){
return resultat;
}else{
return "Ingen biler registrert";
}
}
}// ~Billiste
Object class:
public class Bil {
//Datafelter
private String kjennetegn;
private String merke;
private String type;
Bil nesteBil;
public Bil(String nyK, String nyM, String nyT){
System.out.println("Den får tak i stringene k,m og t - de er ikke null");
kjennetegn = nyK;
merke = nyM;
type = nyT;
nesteBil = null;
System.out.println("Endelse på funksjonen");
}
#Override
public String toString() {
return "Bil [kjennetegn=" + kjennetegn + ", merke=" + merke + ", type="
+ type + ", nesteBil=" + nesteBil + "]";
}
}//~Bil
This is where the error points:
public void nyBil(){
Bil ny = new Bil(regnummertekst.getText(), merke.getText(), type.getText());
bilregister.settInnNyBil(ny);
output.setText(bilregister.toString());
}
And finally the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at BilListeGui.nyBil(BilListeGui.java:79)
at BilListeGui.actionPerformed(BilListeGui.java:86)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I would appreciate all the help I can get.
Thanks in advance
Problem solved, there was no instance of bilregister, thereby giving the error NullPointerException.
The UI has two buttons, browse and submit. I want the user to hit browse to find a file, and then submit to copy it to a different location. However whenever I attempt it, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at me.trevor1134.modinjector.ModInjector$3.actionPerformed(ModInjector.java:154)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
"Submit" button actionPerformed :
#Override
public void actionPerformed(ActionEvent arg0) {
if (mod.exists()) { //line 154 mod is a file object
OS = System.getProperty("os.name").toLowerCase();
detectOS();
modLocation = new File(fullPath);
if (modLocation.exists() && modLocation.isDirectory()) {
Path newP = modLocation.toPath();
Path oldP = mod.toPath();
try {
Files.copy(oldP, newP);
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(frame, "Mod successfully copied to: "
+ fullPath);
System.out.println("Mod successfully copied to: " + fullPath);
}
}
}
Browse button code:
#Override
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser(homePath + "\\Downloads");
FileNameExtensionFilter filter = new FileNameExtensionFilter("ZIP & JAR Files",
"zip", "jar");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File mod = fc.getSelectedFile();
textField.setText(mod.getAbsolutePath());
System.out.println("File: " + mod.getName());
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
I basically want the variable mod to carry on to the Submit area, but because of where it is set, I am unable to do so.
In your "browse" button code you are initializing a local variable mod like this:
final File mod = fc.getSelectedFile();
In the "Submit" button code you are using a class variable mod. Same name, different variables with different scopes.
Try changing:
final File mod = fc.getSelectedFile();
to
mod = fc.getSelectedFile();
with mod being a private class variable.
Also add null check in the "Submit" button code.
as the title says, I'm getting a bunch of exceptions while trying to create several labels off an array into a GridLayout of a 100x100 cells, I believed it was supposed to fit perfectly but as I try to create the Tiles (which are merely an exception to JLabel with x,y and type variables) inside the panel which would represent the map, it seems that something is having trouble drawing them somewhere, been trying to use debug but haven't got any useful information about why it's happening.
This is the pertinent code (don't know if pastebin is against the rules, but it will make my life easier showing it to you all)
GUI class:
package gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUIJuego extends JFrame{
private JButton botonConstruirEscuela = new JButton("Escuela");
private JButton botonConstruirComisaria = new JButton("Comisaria");
private JButton botonConstruirCuartel = new JButton("Cuartel de Bomberos");
private JButton botonConstruirArbol = new JButton("Arbol");
private JButton botonConstruirCasa = new JButton("Casa");
private JButton botonConstruirComercio = new JButton("Comercio");
private JButton botonConstruirIndustria = new JButton("Industria");
private Tile[][] mapaTiles = new Tile[100][100];
private JLabel arcaLabel = new JLabel("Arca");
private JLabel puntosBellezaLabel = new JLabel("Puntos de Belleza");
private JLabel habitantesLabel = new JLabel("Habitantes");
public GUIJuego(){
JPanel panelConstruccion = new JPanel(new GridLayout(7,1));
JPanel panelDatosCiudad = new JPanel(new GridLayout(1,3));
JPanel panelMapa = new JPanel(new GridLayout(100,100));
add(panelConstruccion, BorderLayout.WEST);
panelConstruccion.add(botonConstruirEscuela);
panelConstruccion.add(botonConstruirComisaria);
panelConstruccion.add(botonConstruirCuartel);
panelConstruccion.add(botonConstruirArbol);
panelConstruccion.add(botonConstruirCasa);
panelConstruccion.add(botonConstruirComercio);
panelConstruccion.add(botonConstruirIndustria);
add(panelDatosCiudad, BorderLayout.NORTH);
panelDatosCiudad.add(arcaLabel);
panelDatosCiudad.add(puntosBellezaLabel);
panelDatosCiudad.add(habitantesLabel);
add(panelMapa, BorderLayout.CENTER);
cargarTiles(panelMapa);
}
private void cargarTiles(JPanel panel){
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
mapaTiles[i][j] = new Tile(i, j, 0);
asignarTile(mapaTiles[i][j], panel);
}
}
}
private void asignarTile(Tile tile, JPanel panel){
if(tile.getTipo() == 0){
tile.setText("Pasto");
panel.add(tile);
}
}
}
This is an isolated GUIJuego class, showing what I believe is causing problems:
public class GUIJuego extends JFrame{
private Tile[][] mapaTiles = new Tile[100][100];
public GUIJuego(){
JPanel panelMapa = new JPanel(new GridLayout(100,100));
add(panelMapa, BorderLayout.CENTER);
cargarTiles(panelMapa);
}
private void cargarTiles(JPanel panel){
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100; j++){
mapaTiles[i][j] = new Tile(i, j, 0);
asignarTile(mapaTiles[i][j], panel);
}
}
}
private void asignarTile(Tile tile, JPanel panel){
if(tile.getTipo() == 0){
tile.setText("Pasto");
panel.add(tile);
}
}
}
I believe the issue is within the GUI Class, the demise of my application starting at line 50. This is the dump of the errors it gives me:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getDefaultComponent(Unknown Source)
at java.awt.FocusTraversalPolicy.getInitialComponent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.SequencedEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getDefaultComponent(Unknown Source)
at java.awt.FocusTraversalPolicy.getInitialComponent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.SequencedEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
EDIT: Tile Class
import javax.swing.JLabel;
public class Tile extends JLabel{
private int x, y, tipo;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getTipo(){
return tipo;
}
public void setTipo(int tipo){
if(tipo >= 0 || tipo <= 6)
this.tipo = tipo;
}
public Tile(int x, int y, int tipo) {
this.setX(x);
this.setY(y);
this.setTipo(tipo);
}
}
New information:
What is that black block?
That's what I get in the panel where the map is supposed to be, I don't know if that makes my issue clearer.
Thanks for reading!
In the Tile class don't override getX() and getY() methods. Those are methods defined by JComponent().
Instead maybe use getRow() and getColumn() along with setRow() and setColumn().