Java, Errors with JButton - java

I am trying to make a Login Form with Java. I Cant get it working.
I have looked all over then internet for how to fix this, I can't find anything.
Code:
LoginFrame.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginFrame extends JFrame
{
JPanel pane = new JPanel();
static JFormattedTextField username = new JFormattedTextField(16);
static JFormattedTextField password = new JFormattedTextField(16);
static JButton loginButton = new JButton("Login!");
static String input[];
public LoginFrame() throws IOException
{
super("Login");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(pane);
pane.add(new JLabel("Username"));
pane.add(username);
pane.add(new JLabel("Password"));
pane.add(password);
pane.add(loginButton);
#Override
IEventHandler eHandler = new IEventHandler();
#Override
loginButton.addActionListener(eHandler);
setVisible(true);
}
static String[] getInput()
{
return input;
}
}
IEventHandler.java:
import java.awt.event.*;
class IEventHandler implements ActionListener
{
public void actionPreformed(ActionEvent e)
{
if(e.getSource() == LoginFrame.loginButton){
LoginFrame.loginButton.setEnabled(false);
new AuthLIB().authenticate(LoginFrame.getInput());
}
}
public IEventHandler()
{
System.out.println("Event Handler Hooked");
}
}

You aren't overriding anything with-in the method body. These
#Override
IEventHandler eHandler = new IEventHandler();
#Override
loginButton.addActionListener(eHandler);
should just be
IEventHandler eHandler = new IEventHandler();
loginButton.addActionListener(eHandler);
and assuming you want ActionListener.actionPerformed(ActionEvent)
public void actionPreformed(ActionEvent e)
should use that annotation. You'd see the spelling mistake quicker anyway.
#Override
public void actionPerformed(ActionEvent e)

Related

Hyperlink event type activated error

I am trying to create a simple web browser but when i run it and hover over an URL the URL gets run even though i gave event.getEventType()==HyperlinkEvent.EventType.ACTIVATED
why does it behave like event.getEventType()==HyperlinkEvent.EventType.ENTERED
Here is the full Code
package gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class WebBrowser extends JFrame{
private JTextField addressbar;
private JEditorPane display;
public WebBrowser(){
super("Sagar Browser");
addressbar = new JTextField("Enter a URL");
addressbar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
load(event.getActionCommand());
}
}
);
add(addressbar,BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener(
new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED);
load(event.getURL().toString());
}
}
);
add(new JScrollPane(display),BorderLayout.CENTER);
}
private void load(String usertext){
try{
display.setPage(usertext);
addressbar.setText(usertext);
}catch(Exception e){
System.out.println("Enter Full URL");
}
}
public static void main(String[] args){
WebBrowser w = new WebBrowser();
w.setSize(500,500);
w.setVisible(true);
}
}
Your listener ignores the relevant predicate. You probably meant this:
new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
load(event.getURL().toString());
}
}
}
Related examples are examined here and here.

Needing to return value from user input

a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)

Clear JTextField Contents on Click

So I've built a very basic Web browser - I'm trying desperately to remove the contents of the address bar when a user clicks on it (JTextField) this appears with some text in as default. Any advice is appreciated.
Have a great day!
MY CODE
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Web_Browser extends JFrame {
private final JTextField addressBar;
private final JEditorPane display;
// Constructor
public Web_Browser() {
super("Web Browser");
addressBar = new JTextField("Click & Type Web Address e.g. http://www.google.com");
addressBar.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
loadGo(event.getActionCommand());
}
}
);
add(addressBar, BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener(
new HyperlinkListener(){
#Override
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
loadGo(event.getURL().toString());
}
}
}
);
add(new JScrollPane(display), BorderLayout.CENTER);
setSize(500,300);
setVisible(true);
}
// loadGo to sisplay on the screen
private void loadGo(String userText) {
try{
display.setPage(userText);
addressBar.setText(userText);
}catch(IOException e){
System.out.println("Invalid URL, try again");
}
}
}
Use a FocusListener. On focusGained, select all.
addressBar.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
For example:
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
#SuppressWarnings("serial")
public class FocusExample extends JPanel {
private static final int TF_COUNT = 5;
private JTextField[] textFields = new JTextField[TF_COUNT];
public FocusExample() {
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField("Foo " + (i + 1), 10);
textFields[i].addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
add(textFields[i]);
}
}
private static void createAndShowGui() {
FocusExample mainPanel = new FocusExample();
JFrame frame = new JFrame("FocusExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This gives the user the option of leaving the previous text in place, of adding to the previous text, or of simply over-writing it by typing.
new JTextField("Click & Type Web Address e.g. http://www.google.com");
Maybe you want the Text Prompt, which doesn't actually store any text in the text field. It just gives the user a hint what the text field is for.
This is beneficial so that you don't generate DocumentEvents etc., since you are not actually changing the Document.
Add a mouseListener instead of your actionListener method.
addressBar.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
addressBar.setText("");
}

Responding to Button using KeyBIndings

I want to make a program with these goals:
1) Make a JButton
2) Attach the button to a key (The "A" Key) using KeyBindings
3) Execute some code when "A" is clicked
Here is the code I have so far:
// Imports
Public class Test{
JButton button = new JButton();
//...
Test(){
button.getInputMap().put(KeyStroke.getKeyStroke("A"), "Pressed");
//...
}
// Where do I add the code that responds when button is pressed?
}
Now where do I add the code that I want it to execute when the button is pressed?
Two ways I can think of:
Have JButton and and Key Bindings share the same AbstractAction, or perhaps better
Simply call doClick() on the button from the key binding.
KeyBindingEg.java
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingEg extends JPanel {
private JButton btnA = new JButton();
public KeyBindingEg() {
Action btnAction = new ActionOne("A");
Action keyBindingAction = new ActionTwo();
int condition = JLabel.WHEN_IN_FOCUSED_WINDOW;
InputMap inputmap = btnA.getInputMap(condition);
ActionMap actionmap = btnA.getActionMap();
final String aKeyPressed = "a key pressed";
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aKeyPressed );
actionmap.put(aKeyPressed, keyBindingAction);
// actionmap.put(aKeyPressed, btnAction); // one or the other, your choice
btnA.setAction(btnAction);
add(btnA);
}
private class ActionOne extends AbstractAction {
public ActionOne(String text) {
super(text);
}
#Override
public void actionPerformed(ActionEvent e) {
sharedMethod();
}
}
private class ActionTwo extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
btnA.doClick();
}
}
private void sharedMethod() {
System.out.println("Method called by either key bindings or action listener");
}
private static void createAndShowGui() {
JFrame frame = new JFrame("KeyBindingEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new KeyBindingEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
you need to add an action listener, specificaly for actionPerformed. declare this somewhere inside your constructor:
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] argv) throws Exception {
JButton component = new JButton();
MyAction action = new MyAction();
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
action.getValue(Action.NAME));
}
}
class MyAction extends AbstractAction {
public MyAction() {
super("my action");
}
public void actionPerformed(ActionEvent e) {
//Here goes the code where the button does something
System.out.println("hi");//In this case we print hi
}
}
In this example if we press F2 it will be the equivalent of pressing the button.

Null pointer exception error

When I run my program I get this error nullPointerException: null.
import model.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
public class ButtonPanel extends JPanel implements View
{
private Prison prison;
private LeftInputPanel leftInput;
private DaysPanel days;
private MonthsPanel months;
private YearsPanel years;
private CrimePanel crime;
private AllocateListener aListener;
public ButtonPanel()
{
setup();
build();
}
public void setup()
{
}
public void build()
{
JButton button = new JButton("Allocate Cell");
Dimension size = new Dimension(240, 70);
button.setPreferredSize(size);
button.setMinimumSize(size);
button.setMaximumSize(size);
button.addActionListener(aListener);
add(button);
update();
}
public void update()
{
leftInput.update(); //ERROR ON THIS LINE
}
private class AllocateListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Criminal criminal = new Criminal(leftInput.name());
Period period = new Period(days.days(), months.months(), years.years());
criminal.set(new Crime(crime.getCrime()));
prison.add(criminal);
}
}
}
My LeftInputPanel - where I call the update method from.
import model.*;
import java.awt.*;
import java.text.*;
import javax.swing.*;
public class LeftInputPanel extends JPanel
{
public JTextField field = new JTextField();
public LeftInputPanel()
{
setup();
build();
}
public void setup()
{
//setLayout(new GridLayout());
Dimension size = new Dimension(100, 190);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
}
public void build()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel(" Name");
field.setPreferredSize(new Dimension(90, 20));
add(label);
add(field);
add(new DaysPanel());
add(new MonthsPanel());
add(new YearsPanel());
}
public String name()
{
return field.getText();
}
public void update()
{
field.setText("");
}
}
Errors
java.lang.NullPointerException
at ButtonPanel.update(ButtonPanel.java:43)
at ButtonPanel.build(ButtonPanel.java:38)
at ButtonPanel.<init>(ButtonPanel.java:21)
at RightInputPanel.build(RightInputPanel.java:30)
at RightInputPanel.<init>(RightInputPanel.java:14)
at InputPanel.build(InputPanel.java:24)
at InputPanel.<init>(InputPanel.java:13)
at Panel.build(Panel.java:30)
at Panel.<init>(Panel.java:13)
at Window.build(Window.java:31)
at Window.<init>(Window.java:11)
at Root.main(Root.java:9)
aListener hasn't been initialized (ie it is still null) and you're trying to add it as an action listener. I suspect all that's required is:
private AllocateListener aListener = new AllocateListener();
When you get an exception, you generally get a stack trace, including the full call sequence - that's an invaluable help in tracking down the problem.
If you cannot figure out the problem from that stack trace, you need to supply it to us along with the relevant code, with line numbers.
Then we'll be better able to help you out by finding the problem and, more importantly, showing you how it's done.

Categories

Resources