I am trying to write a file processing application but the program won't wait for the user to select a file before moving and finishing the function. I've tried to use wait() and notify() to make it stop but the program now freezes and buttons d and e never show up.
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
public class pdfEditor {
static JFrame inter = new JFrame("The Point Updater");
static JLabel reminder = new JLabel("Please select a function:");
static boolean i = false;
JButton a, b, c, d, e;
JFileChooser fc;
public static void main(String[] args) {
//Sets the window
inter.setSize(750, 250);
inter.setLocation(100, 150);
inter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inter.setLayout(null);
//Label for commands for the user
reminder.setBounds(50, 50, 650, 30);
//add a button
JButton b = new JButton("Update Trainings");
b.setBounds(50, 150, 135, 30);
JButton c = new JButton("Update Employees");
c.setBounds(200, 150, 140, 30);
JButton a = new JButton("Export Points");
a.setBounds(355, 150, 135, 30);
//add them to the frame
inter.add(reminder);
inter.add(a);
inter.add(b);
inter.add(c);
inter.setVisible(true);
//Process selection
//TODO add catches for unformatted spreadsheets
a.addActionListener(new ActionListener() { //If export Points button is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Kashikomarimashita!");
exportPoints();
}
});
b.addActionListener(new ActionListener() { //If update trainings is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Make sure the type is Individual Completions and the columns are set to Training, Employee and Date.");
File file = null;
try {
file = requestInputSpreadsheet();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTraining(file);
}
});
c.addActionListener(new ActionListener() { //If update employees is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Please import a employee list from iScout or Quickbase.");
File file = null;
try {
file = requestInputSpreadsheet();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateEmployees(file);
}
});
}
//Asks the user for a spreadsheet to be used in processing.
public static File requestInputSpreadsheet() throws InterruptedException{
//makes file chooser
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new SpreadsheetFilter());
fc.setAcceptAllFileFilterUsed(false);
//makes new buttons and label
JLabel name = new JLabel();
name.setBounds(180, 100, 270, 30);
JButton d = new JButton("Choose File...");
d.setBounds(50, 100, 135, 30);
JButton e = new JButton("Go!");
e.setBounds(450, 100, 50, 30);
inter.add(d);
SwingUtilities.updateComponentTreeUI(inter);
//switch for the file chooser if file was chosen successfully
i = false;
File file = null;
d.addActionListener(new ActionListener() { //begins file choosing process
#Override
public void actionPerformed(ActionEvent arg0) {
int returnVal = fc.showOpenDialog(inter);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//processes file and displays name
File file = fc.getSelectedFile();
name.setName(file.getName());
inter.add(name);
inter.add(e);
SwingUtilities.updateComponentTreeUI(inter);
}
}
});
e.addActionListener(new ActionListener() { //returns the selected file
#Override
public void actionPerformed(ActionEvent arg0) {
i = true;
synchronized (e) {
e.notify();
}
}
});
synchronized(e) {
e.wait();
}
//removes the button!
inter.remove(d);
inter.remove(e);
SwingUtilities.updateComponentTreeUI(inter);
if (i == true) {
return file;
}
return null;
}
//Updates completed training list and awards points based on a spreadsheet exported from the database
public static boolean updateTraining(File file) {
// still working on the processing
if (file == null) {
return false;
} else {
System.out.println("Updated Training!!");
return true;
}
}
//Updates the employee list using an employee list exported from the database
public static boolean updateEmployees(File file) {
if (file == null) {
return false;
} else {
System.out.println("Updated Employees!!");
return true;
}
}
//Creates and exports a spreadsheet with employee names and current points
public static boolean exportPoints() {
System.out.println("Exported Points!");
return true;
}
}
I included all of the code just in case.
So i just started with eclipse and java script and i am also a new coder. I started of wtih this random name picker project. And the code is written like this:
public static void gods() {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
public static void roles() {
String[] roles = {" Solo", " Jungle", " Mid", " ADC", " Support"};
List<String> names = Arrays.asList(roles);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");}
public void Randomize() {
System.out.println("Here you have your god:");
gods();
System.out.println("Here you have your role:");
roles();}
But i want to import or set in this code inside my windowbuilder plugin. I have tried inserting it inside a JButton as an "actionPerformed" but when i launched the program and clicked the button it opened up the console in eclipse when i want it to open inside the program.
This is my windowbuilder code:
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Plswork() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtAronErDu = new JTextField();
txtAronErDu.setFont(new Font("SWTOR Trajan", Font.PLAIN, 22));
txtAronErDu.setText("Aron er du homofil?");
txtAronErDu.setBounds(0, 0, 434, 39);
frame.getContentPane().add(txtAronErDu);
txtAronErDu.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(199, 118, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}
PS: This is how it looks when i imoprt it:
public class Plswork {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Sebbe");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
});
btnNewButton.setBounds(167, 117, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}
I want to know how my console output can be save in a notepad file?
import java.awt.EventQueue;
public class HLS1 {
private JFrame frmHttpsLiveStreaming;
private JTextField textField;
// file is accessed to the whole class
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HLS1 window = new HLS1();
window.frmHttpsLiveStreaming.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HLS1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHttpsLiveStreaming = new JFrame();
frmHttpsLiveStreaming.setTitle("HTTPS Live Streaming");
frmHttpsLiveStreaming.setBounds(100, 100, 494, 112);
frmHttpsLiveStreaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHttpsLiveStreaming.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Open File");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Argument:" + arg0);
JFileChooser fs = new JFileChooser(new File("c:\\"));
fs.setDialogTitle("Open a file");
fs.setFileFilter(new FileTypeFilter(".m3u8", ""));
fs.setFileFilter(new FileTypeFilter(".m3u", ""));
fs.showOpenDialog(null);
file = fs.getSelectedFile();
textField.setText(file.getAbsolutePath());
}
});
btnBrowse.setBounds(336, 7, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnBrowse);
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("");
}
});
btnNewButton_1.setBounds(237, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton_1);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(83, 11, 24, 14);
frmHttpsLiveStreaming.getContentPane().add(lblUrl);
textField = new JTextField();
textField.setBounds(116, 11, 210, 19);
frmHttpsLiveStreaming.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Check");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
List<String> fileArray = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Scanner s = null;
if(textField.getText().matches(regex)){
URL url = new URL(textField.getText());
s= new Scanner(url.openStream());
}else{
s = new Scanner(new BufferedReader(new FileReader(file)));
}
if(s != null){
while(s.hasNextLine()){
String line = s.nextLine();
if(!line.isEmpty()){
fileArray.add(line);
}
System.out.println(line);
}
}
s.close();
errors.addAll(validateEXTM3U(fileArray));
for (String error : errors) {
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(126, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton);
}
private List<String> validateEXTM3U(List<String> fileArray){
List<String> errors = new ArrayList<String>();
String tag = fileArray.get(0);
if(!tag.equals("#EXTM3U")){
errors.add("First line in the menifest file is not #EXTM3U");
}
return errors;
}
}
It could be a hacky solution , but if you are running in windows or linux then you can pipe / redirect it.
java HLS1 > notepad.txt
if not what you are looking for , then why not using something called log4j ?
Why don't you write your own utility that has an public static void output(String output) method. Then instead of using System.out.println("...") you call output("...") then in your output(String output) method you can do anything with the output, like first write to the file, then print to the console.
Hope this helps.
i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.
I keep getting an NullPointerException, and I dont know why. what the class is supposed to do, is to send whatever I write in my jtextfield as writeUTF, but I keep getting a NullPointerException at
dos = new DataOutputStream(socket.getOutputStream());
The GUI code:
public class GUI {
private JFrame frame = new JFrame("Dryck & Ingrediens"); // GUI
private JTextField jtf = new JTextField();// GUI
private JTextArea jl1 = new JTextArea();// GUI
private JList jl = new JList();// GUI
private JScrollPane js = new JScrollPane(jl);// GUI
private DataOutputStream dos;// ServerHandler
private JLabel lab = new JLabel("Ange dryck");//GUI
private JLabel lab1 = new JLabel("Walid Shams");
private JLabel lab2 = new JLabel("Kushtrim Brahimi");
private HashMap<String, ArrayList<String>> drinkar = null;//Controller
private DataInputStream dis;
private Socket socket;
private ServerHandler serverH;
public GUI() {
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 300, 420, 400);
frame.setResizable(false);
frame.setVisible(true);
js.add(jl);
js.add(jl1);
jl1.setEditable(false);
lab.setBounds(170, 20, 130, 20);
lab1.setBounds(300, 310, 130, 20);
lab2.setBounds(300, 330, 130,20);
jtf.setBounds(130, 40, 150, 40);
jl.setBounds(50, 90, 150, 200);
jl1.setBounds(210, 90, 150, 200);
Container con = frame.getContentPane();
con.setBackground(Color.cyan);
This is where the error accures and where i get the nullpointerexception everytime i type something in my jtextfield.
jtf.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (dos == null) {
if (jtf.getText().length() > 0) {
try {
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(jtf.getText());
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String[] empty = new String[]{""};
jl.setListData(empty);
}
}
}
}
);
jl.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (jl.getSelectedIndex() != -1) {
String item = (String) jl.getSelectedValue();
jl1.setText("");
for (String ingrediens : drinkar.get(item)) {
jl1.append(ingrediens + "\n");
}
}else{
jl1.setText("");
}
}
});
frame.add(jtf);
frame.add(jl);
frame.add(jl1);
frame.add(lab);
frame.add(lab1);
frame.add(lab2);
frame.add(js);
}
// tar emot arrayen, lagrar i ny array och visar i JList
public void getArrayList() {
String[] arr = null;
for(int i = 0; i < arr.length; i++){
arr = serverH.setList();
}
jl.setListData(arr);
}
public static void main(String[] args) {
GUI g = new GUI();
}
}
Regarding:
dos = new DataOutputStream(socket.getOutputStream());
The only variable that can throw an NPE on this line is socket which begs the question: where do you initialize socket?
Answer: you don't.
Solution: fix this.
Please always check the variables on the line that throws the NPE as that will show you the cause for the error 99% of the time. You haven't appeared to have tried to do this yet.
You define an instance variable »serverH«
private ServerHandler serverH;
but don't assign any object to it. Therefore you should be facing the NullPointerException. You should assign an object to it, e.g.
serverH = new ServerHandler();
This should solve your problem regarding the NullPointerException.