I have created simple gui application using JFilechooser for opening a pdf file. The gui has a browse button and a textArea to visualize the contents of the file.
I have created two classes: Gui(contains main()) and GuiJFrame to implement the gui, handlers and listeners. I have managed to get the window app but the browse button doesn't seem to work. I don't know where I have made a mistake, please help me
import java.awt.EventQueue;
public class Gui {
/** Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui window = new Gui();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** Create the application. */
public Gui() {
initialize();
}
/** Initialize the contents of the frame. */
private void initialize() {
GuiJFrame guiJFrame = new GuiJFrame();
guiJFrame.setVisible(true);
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class GuiJFrame extends JFrame {
private JButton btnBrowse;
private JTextArea log, filtered_log;
public GuiJFrame() {
this.setTitle("TikaExtractorGui");
this.setBounds(100, 100, 700, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panel_1 = new JPanel();
this.getContentPane().add(panel_1, BorderLayout.NORTH);
JPanel panel_2 = new JPanel();
this.getContentPane().add(panel_2, BorderLayout.CENTER);
/*
* BUTTONS *
*/
JButton btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
/*
* Text_Areas*
*/
JTextArea log = new JTextArea(50, 30);
panel_2.add(log);
log.setEditable(false);
/*
* LAYOUT *
*/
setLayout(new FlowLayout());
add(panel_1, FlowLayout.CENTER);
add(panel_2, FlowLayout.LEFT);
JScrollPane logScrollPane1 = new JScrollPane(log);
logScrollPane1.setSize(300, 300);
add(logScrollPane1);
/*
* Setting the handlers *
*/
ActionHandler a_handler = new ActionHandler();
btnBrowse.addActionListener(a_handler);
}
private class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
TikaExtractorInterface ex = new TikaExtractor();
PDFParser parser = new PDFParser();
String g = null;
if (event.getSource() == btnBrowse) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(log);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file.getName().endsWith("pdf")) {
file.getPath();
if (file != null) {
try {
g = ex.extractFromFile(parser, file);
log.setText(g);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
I know why it is not working.
Change
/* BUTTONS *
* */
JButton btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
to
/* BUTTONS *
* */
btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
this:
if(event.getSource() == btnBrowse)
should be
if(event.getSource().equals(btnBrowse))
You can't use the == to identify an equal object in java, you always have to use equals() to make sure that two objects are the same.
This:
JButton btnBrowse = new JButton("Browse");
should be
btnBrowse = new JButton("Browse");
You are shadowing your class member variable with a local one so the if clause always comapres against a null value. The btnBrowse is never stored in your class.
I would say add a System.out.println at the entry of actionPerformed method and check if that is being called indeed.
Also its better to use action commands for each button, so that you don't have to check for equality of event source. Something like this:
btnBrowse.setActionCommand("Browse"); //before attaching the listener
and then in the actionPerformed
String actionCommand = event.getActionCommand();
if("Browse".equals(actionCommand)) {
JFileChooser fileChooser = new JFileChooser();
int retVal = fileChooser.showOpenDialog(null);
}
Browse button should be given as argument for filechooser.
int returnVal = fc.showOpenDialog(log);
should be,
int returnVal = fc.showOpenDialog(btnBrowse);
Related
I wanna create a simple java application, and I have some problems.
This is my main class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("First B");
panel.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SecWindow SW = new SecWindow();
//-----
}
});
}
}
Secound class:
import javax.swing.JButton;
import javax.swing.JPanel;
public class SecWindow {
public SecWindow() {
SecPanel();
}
public void SecPanel() {
JPanel panel2 = new JPanel();
JButton btnNewButton_2 = new JButton("Sec B");
panel2.add(btnNewButton_2);
}
}
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
You should be using a CardLayout. The CardLayout will allow you to swap panels in the frame.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example uses a combo box to swap the panels so you just need to move that code to the ActionListener of your button.
try{
secWindow secondWindow = new secWindow();
secondWindow.frame.setVisible(true);
window.frame.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
This will hide first window and show second one.
You can not completely "delete" object that has main method in it. your app will start and end in main method.
instead you can make new class and transfer main method over there
I am using WindowBuilder to create a GUI.
I'm kinda new to JFrame and I have a problem: I added a JSpinner and I want to save the number that I put in my spinner to an int so I can use it later on. Can someone please help me? Thanks.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class frame1 {
private JFrame frame;
private JTextField txtHoeveelEuroWil;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(20, 20, 500, 20));
spinner.setBounds(116, 100, 200, 50);
frame.getContentPane().add(spinner);
int value;
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//value=Integer.parseint ???
//what should I type here to save the number that I entered
//in the spinner?
}
});
btnNewButton.setBounds(172, 177, 89, 32);
frame.getContentPane().add(btnNewButton);
}
}
Try this
try {
spinner.commitEdit();
}
catch (ParseException pe) {{
// Edited value is invalid, spinner.getValue() will return
// the last valid value, you could revert the spinner to show that:
JComponent editor = spinner.getEditor()
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setValue(spinner.getValue());
}
// reset the value to some known value:
spinner.setValue(fallbackValue);
// or treat the last valid value as the current, in which
// case you don't need to do anything.
}
int value = (Integer)spinner.getValue();
To save the value and use it, you can set a field variable to hold it. So in your fram1 class, add a getter and setter for the variable. Then set the variable on button click.
public class frame1 {
//default to -1
private int spinnerValue = -1;
private void setSpinnerValue(aValue) {
spinnerValue = aValue;
}
public int getSpinnerValue() {
return spinnerValue;
}
private void initialize() {
// blah blah
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// here set a value
setSpinnerValue((Integer) spinner.getValue());
}
});
}
}
then when you need the value, you can use the instance of frame1 and call this method
frame1.getSpinnerValue();
So if a user do not press any button,the action listener is not triggered and i end up with an exception. So i thought to put a default String in my FrameClass and change that String whenever a button is clicked,than in my main class i do a loop that keeps on looping until the default String is changed,so i think it is an infinite loop. Is it okay to do that ?
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
/**
*
* #author E-TECH
*/
public class ButtonsFrame extends JFrame {
private JButton ScPerF, weekSc, both,cancel;
private SchedulePerWeek week;
private CoursesPerWeek course;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
ScPerF = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice="nothing";
ScPerF.addActionListener(new ButtonListener());
weekSc.addActionListener(new ButtonListener());
both.addActionListener(new ButtonListener());
cancel.addActionListener(new ButtonListener());
setResizable(false);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(ScPerF);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
getContentPane().add(panel);
setVisible(true);
pack();
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == ScPerF) {
dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
dispose();
choice = "course";
}
if (event.getSource() == both) {
dispose();
choice = "both";
}
if (event.getSource()==cancel){
dispose();
choice="cancel";
}
}
}
public boolean Activated() {
return ScPerF.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
}
public class SchedulePerWeek {
HSSFSheet weekSh,courseSh;
int instructor_count;
HSSFWorkbook wb;
public SchedulePerWeek() {
ExcelReader reader = new ExcelReader();
HSSFSheet sh = reader.getSortedSheet();
String choice=reader.getChoice();
if(choice.equals("cancel")||choice.equals("nothing")){///i fixed the exception with this condition by closing the program instead of continuing,but i want to wait for the user instead of just exiting the program
System.exit(1);
}
wb = new HSSFWorkbook();
/////
///more code
I ran your code from a couple of edits ago, and it works fine on my Windows 8 workstation, Java 7.
Before you go much further in your GUI design, read this answer to The Use of Multiple JFrames, Good/Bad Practice?
I modified your code to use a JFrame, rather than extend one. You should only extend a Swing component when you override one of the component methods.
You only need to define your Button listener once. You set the listener on your buttons.
I changed the JFrame default close operation to exit on close.
I added a main method so I could run your code.
Here's the code with the changes.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
/**
*
* #author E-TECH
*/
public class ButtonsFrame{
private JButton scPerf, weekSc, both, cancel;
// private SchedulePerWeek week;
// private CoursesPerWeek course;
private JFrame frame;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scPerf = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice = "nothing";
ButtonListener listener = new ButtonListener();
scPerf.addActionListener(listener);
weekSc.addActionListener(listener);
both.addActionListener(listener);
cancel.addActionListener(listener);
frame.setResizable(false);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(scPerf);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == scPerf) {
frame.dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
frame.dispose();
choice = "course";
}
if (event.getSource() == both) {
frame.dispose();
choice = "both";
}
if (event.getSource() == cancel) {
frame.dispose();
choice = "cancel";
}
}
}
public boolean Activated() {
return scPerf.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonsFrame();
}
});
}
}
I'm trying to create an Onscreen telepad where people can press the keypad buttons and itll come up in the text box I haven't made the ActionListner for the keypad yet but I want it to show up in the view... Here's the code for the Keypad Panel and the View there is also a duration timer which I've managed to get working but can't put them into one view
Here's the Keypad Panel
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel {
private JButton noStar;
private JButton noHash;
private JButton[] buttons;
private JButton C;
private JButton add;
private JPanel keypadPanel;
public KeypadPanel(TelepadController controller) {
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("" + i);
// buttons[i].addActionListener(controller.new NumberButtonListener());
}
//noStar.addActionListener(controller.new noStarActionListener);
//noHash.addActionListener(controller.new noHashActionListener);
//C.addActionListener(controller.new CActionListener);
//add.addActionListener(controller.new addActionListener);
noStar = new JButton("*");
noHash = new JButton("#");
C = new JButton("C");
add = new JButton("+");
JPanel keypadPanel = new JPanel();
keypadPanel.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++) {
keypadPanel.add(buttons[i]);
add(noStar);
add(noHash);
add(C);
add(add);
}
}
}
And here's the code for the main View
package londontelepad2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.apache.commons.beanutils.BeanUtils;
public class TelepadView implements Observer {
private StopwatchPanel stopwatchPanel;
private KeypadPanel keypadPanel;
private JFrame frame;
/**
*
* #param controller
*/
public TelepadView(TelepadController controller) {
super();
this.setResources();
frame = new JFrame("London Telepad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stopwatchPanel = new StopwatchPanel(controller);
//stopwatchPanel = new StopwatchPanel2(controller);
keypadPanel = new KeypadPanel(controller);
frame.getContentPane().add(stopwatchPanel);
frame.getContentPane().add(keypadPanel);
frame.pack();
}
public void show() {
frame.setVisible(true);
}
#Override
public void update(Observable observable, Object arg) {
if (arg.equals(Properties.TIME)) {
try {
stopwatchPanel.setTime(BeanUtils.getProperty(observable,
Properties.TIME));
} catch (Exception e) {
System.out.println(e);
}
}
}
public void setResetState() {
stopwatchPanel.setButtons(true, false, false);
}
public void setStoppedState() {
stopwatchPanel.setButtons(false, false, true);
}
public void setRunningState() {
stopwatchPanel.setButtons(false, true, false);
}
private void setResources() {
ColorUIResource defaultBackground = new ColorUIResource(Color.white);
ColorUIResource defaultForeground = new ColorUIResource(Color.black);
ColorUIResource disabledColor = new ColorUIResource(Color.lightGray);
FontUIResource smallFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 12));
FontUIResource bigFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 14));
UIManager.put("Button.background",
defaultBackground);
UIManager.put("Button.foreground",
defaultForeground);
UIManager.put("Button.disabledText",
disabledColor);
UIManager.put("Button.font", smallFont);
UIManager.put("Label.background",
defaultBackground);
UIManager.put("Label.foreground",
defaultForeground);
UIManager.put("Label.font", bigFont);
UIManager.put("Panel.background",
defaultBackground);
UIManager.put("Panel.foreground",
defaultForeground);
}
}
If I do the .add seperately I get an error to do with (actual and formal argument lists differ in length)
and if i do it together I get java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
And I can't find what it is im doing wrong!!
All the help in the world would be very appreciated seeing as I'm an Uber noob at java!
Thank you
Bilal
UPDATE
Here's a log of the error I reciveve when I put them in the same .add field
Exception in thread "main" java.lang.NullPointerException
at londontelepad2.KeypadPanel.<init>(KeypadPanel.java:48)
at londontelepad2.TelepadView.<init>(TelepadView.java:46)
at londontelepad2.TelepadController.<init>(TelepadController.java:33)
at londontelepad2.LondonTelepad2.main(LondonTelepad2.java:19)
Java Result: 1
Wait, KeypadPanel is just a plain object. Why doesn't it extend JPanel?
you are calling the add()-method of a JFrame to add your components to the frame? You need to call
frame.getContentPane().add(comp);
I have a Java program which until now used to get the input from command line and then proceed accordingly.
Now, I want to have a basic GUI for this. It will need a few buttons which will trigger the events. I am experienced in HTML and JavaScript. Is it possible to write in HTML (or similar syntax) to generate the GUI?
I don't want to go in Swing and awt solution, because I would rather concentrate on the main program than on the GUI.
Here's another alternative. See also How to Use HTML in Swing Components.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see http://stackoverflow.com/a/10067256/230513
* #see http://stackoverflow.com/a/7454691/230513
*/
public class Pathfinder extends JPanel {
private static final int TEXT_SIZE = 32;
private JTextField srcField = new JTextField(TEXT_SIZE);
private JTextField dstField = new JTextField(TEXT_SIZE);
private JTextField valueField1 = new JTextField(TEXT_SIZE);
private JTextField valueField2 = new JTextField(TEXT_SIZE);
private String srcPath, dstPath, value1, value2;
public Pathfinder() {
super(new GridLayout(0, 1));
this.add(createPathPanel("Source Directory", srcField));
this.add(createPathPanel("Target Directory", dstField));
this.add(createFieldPanel("Some Value:", valueField1));
this.add(createFieldPanel("Another Value:", valueField2));
JPanel submitPanel = new JPanel();
submitPanel.add(new JButton(new AbstractAction("Submit") {
#Override
public void actionPerformed(ActionEvent e) {
srcPath = srcField.getText();
dstPath = dstField.getText();
value1 = valueField1.getText();
value2 = valueField2.getText();
process();
}
}));
this.add(submitPanel);
}
private void process() {
// see ProcessBuilder http://stackoverflow.com/questions/5740390
System.out.println(srcPath);
System.out.println(dstPath);
System.out.println(value1);
System.out.println(value2);
}
private JPanel createPathPanel(String name, final JTextField jtf) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel.add(new JButton(new AbstractAction(name) {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(
new File(System.getProperty("user.dir")));
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = jfc.showOpenDialog(Pathfinder.this);
if (result == JFileChooser.APPROVE_OPTION) {
jtf.setText(jfc.getSelectedFile().getPath());
}
}
}));
panel.add(jtf);
return panel;
}
private JPanel createFieldPanel(String name, JTextField jtf) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel.add(new JLabel(name));
panel.add(jtf);
return panel;
}
private void display() {
JFrame f = new JFrame("Pathfinder");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Pathfinder pf = new Pathfinder();
if (args.length > 0) {
pf.srcPath = args[0];
pf.dstPath = args[1];
pf.process();
} else {
pf.display();
}
}
});
}
}
I want to have a basic GUI for this. It will need a few buttons which will trigger the events.
This 'basic GUI' goes slightly beyond the spec. to add an output area.
import java.awt.*;
import javax.swing.*;
class SimpleEventGUI {
SimpleEventGUI() {
JPanel gui = new JPanel(new BorderLayout());
JToolBar toolBar = new JToolBar();
for (int ii=1; ii<6; ii++) {
toolBar.add(new JButton("Event " + ii));
if (ii%2==0) {
toolBar.addSeparator();
}
}
gui.add(toolBar, BorderLayout.NORTH);
gui.add( new JScrollPane(new JTextArea(5,30)), BorderLayout.CENTER );
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SimpleEventGUI();
}
});
}
}
You may consider Google Web Toolkit with Window Builder which allow you to build a rich internet interface using Java and interact with the existing logic.
If you want something quick, you can build a Swing GUI using Window Builder