I am trying to make a button that says hello world but it dose not work I tried multiple times but nothing i did made a difference
[![package com.company;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main implements ActionListener {
JButton b;
JFrame f;
public Main()
{
b=new JButton("hello");
b.addActionListener(this);
b.setBounds(100,100,95,30);
f.setTitle("first");
f.setSize(500,300);
f.add(b);
f.setVisible(true);
f.setLayout(null);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b)
{
System.out.print("hello world");
}
}
public static void main(String\[\] args) {
// write your code here
new Main();
}
}][1]][1]
and this is he result it displays
You need to instantiate your JFrame in the constructor with f = new JFrame();.
Related
I need to access variables from another class and I have done it using 2 different approaches described below.
My question is which of the two is preferable and why since both work quite nicely -or is there another better way to do it?. I have also done it using internal classes but this is inconvenient when the number of code lines gets growing ever larger.
In the following test code the commented asterisks repesent different files:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame f = new MainFrame("Testing",50,50);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
//**********************************************************************
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame(String title,int x,int y) {
setTitle(title);
this.setLocation(x, y);
UpperPanel pUp=new UpperPanel();
add(pUp, BorderLayout.NORTH);
LowerPanel pLow=new LowerPanel();
add(pLow, BorderLayout.SOUTH);
pack();
}
}
Now as you can see below UpperPanel must access JButtons from LowerPanel and LowerPanel must access the menu from UpperPanel. For this reason I could pass pUp as a parameter to the LowerPanel constructor but I can't pass pLow as parameter to UpperPanel as it hasn't been created yet.
Therefore I have used 2 methods, one declaring instances of the relevant classes and the other using static variables. The previous 2 classes above are the same in each approach.
Below is the code of the panels in the first case:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JPanel;
public class LowerPanel extends JPanel implements ActionListener {
static JButton butEnableMenu;
static JButton butEnableBut1;
public LowerPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
butEnableMenu=new JButton("Enable menu");
butEnableMenu.setEnabled(true);
butEnableMenu.addActionListener(this);
add(butEnableMenu);
butEnableBut1=new JButton("Enable first button");
butEnableBut1.setEnabled(false);
butEnableBut1.addActionListener(this);
add(butEnableBut1);
}
public void actionPerformed(ActionEvent e) {
UpperPanel up = null;
Object clicked=e.getSource();
JMenu mnu=up.myMenuBar.getMenu(0);
if(clicked.equals(butEnableMenu)) {
mnu.setEnabled(true);
butEnableMenu.setEnabled(false);
}
else if(clicked.equals(butEnableBut1)) {
butEnableMenu.setEnabled(true);
butEnableBut1.setEnabled(false);
}
}
}
//**********************************************************************
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class UpperPanel extends JPanel {
static JMenuBar myMenuBar;
public UpperPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
myMenuBar=new JMenuBar();
JMenu but2=new JMenu("2nd button");
JMenuItem enableBut2=new JMenuItem("Enable");
but2.setEnabled(false);
enableBut2.addActionListener(new menuActionListener());
myMenuBar.add(but2);
but2.add(enableBut2);
add(myMenuBar);
}
}
class menuActionListener implements ActionListener {
static String clickedMenuItem=null;
LowerPanel lp;
public void actionPerformed(ActionEvent e) {
clickedMenuItem=e.getActionCommand();
JMenuItem mnuItm=(JMenuItem)e.getSource();
JPopupMenu pmen = (JPopupMenu)mnuItm.getParent();
JMenu pmnu =(JMenu)pmen.getInvoker();
if(clickedMenuItem.equals("Enable")) {
pmnu.setEnabled(false);
lp.butEnableBut1.setEnabled(true);
}
}
}
And these are the panels in the second case:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class UpperPanel extends JPanel {
static JMenuBar myMenuBar;
public UpperPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
myMenuBar=new JMenuBar();
JMenu but2=new JMenu("2nd button");
JMenuItem enableBut2=new JMenuItem("Enable");
but2.setEnabled(false);
enableBut2.addActionListener(new menuActionListener());
myMenuBar.add(but2);
but2.add(enableBut2);
add(myMenuBar);
}
}
class menuActionListener implements ActionListener {
static String clickedMenuItem=null;
public void actionPerformed(ActionEvent e) {
clickedMenuItem=e.getActionCommand();
JMenuItem mnuItm=(JMenuItem)e.getSource();
JPopupMenu jpm = (JPopupMenu)mnuItm.getParent();
JMenu pmnu =(JMenu)jpm.getInvoker();
if(clickedMenuItem.equals("Enable")) {
pmnu.setEnabled(false);
LowerPanel.butEnableBut1.setEnabled(true);
}
}
}
//**********************************************************************
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JPanel;
public class LowerPanel extends JPanel implements ActionListener {
static JButton butEnableMenu;
static JButton butEnableBut1;
public LowerPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT));
butEnableMenu=new JButton("Enable menu");
butEnableMenu.setEnabled(true);
butEnableMenu.addActionListener(this);
add(butEnableMenu);
butEnableBut1=new JButton("Enable first button");
butEnableBut1.setEnabled(false);
butEnableBut1.addActionListener(this);
add(butEnableBut1);
}
public void actionPerformed(ActionEvent e) {
Object clicked=e.getSource();
JMenu mnu=UpperPanel.myMenuBar.getMenu(0);
if(clicked.equals(butEnableMenu)) {
mnu.setEnabled(true);
butEnableMenu.setEnabled(false);
}
else if(clicked.equals(butEnableBut1)) {
butEnableMenu.setEnabled(true);
butEnableBut1.setEnabled(false);
}
}
}
In general there are 2 ways to access a variable from another class:
You create an object of that class. Then this object has all the variables from the scope of that class assigned to it. For example:
Test t = new Test();
t.name = "test";
You can also create a static variable. Then the variable is assigned to the class not the object of that class. This way you will not need to create an object, but all instances of the class will share the same variable.
//In the scope of the class
static String name;
-------------------------
//when classing the class
Test.name = "The Name of the Test";
If you do not want to create a new instance of a class every time, and always use the same instance, you can create a singleton object. You write a getter method that gets you the object. It looks like this:
public class Test {
Test t;
public static void main(String[] args) {
t = new Test();
}
public Test getTest() {
if (t != null) {
return t;
} else {
t = new Test();
return t;
}
}
}
I see you work with a JFrame. Then you will probably want to make it a singleton. Else you will open a new instance of the JFrame every time you call upon it, which is not recommended.
Does this answer your question?
Ok so I will try to make this as understandable as possible. I have created a simple GUI with an "open" button and a textArea (along with other stuff but that's not important right now). Basically I am creating a method that when I click the Open button it displays the contents of the file in the textArea. I believe 99% of the method I have written is correct but I keep getting a NullPointerException and I don't quite understand why. Hopefully my code will clear up any confusion on what I am asking, I will comment on the line of code where I get the exception. Here is my code:
Application class (Basic setup of my GUI):
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class Application extends JFrame {
public OutputPanel outPanel = new OutputPanel();
public BarcodePanel barPanel = new BarcodePanel();
public ButtonPanel btnPanel = new ButtonPanel();
public ReferencePanel refPanel = new ReferencePanel();
public Application() {
super("Book Processor");
this.setLayout(new BorderLayout());
btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
outPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
refPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(btnPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.WEST);
add(refPanel,BorderLayout.SOUTH);
}//end constructor
public static void main(String[] args) {
Application frame = new Application();
frame.setSize(1000,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end main
}//end class
The next set of code is my ButtonPanel class(this is where I am having an issue) So I have an openFile method, that when I click the button it should display the contents of the file in the textArea. Again I receive a NullPointerException and I do not understand why. Here is the code for this class:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel{
JButton btnOpen = new JButton("Open");
OutputPanel outPanel = new OutputPanel();
Scanner input;
public ButtonPanel() {
ButtonHandler handler = new ButtonHandler();
add(btnOpen);
btnOpen.addActionListener(handler);
}//end constructor
/**
* Method for displaying the file onto the textArea.
*
*/
private void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
String fileName;
fileName = chooser.getSelectedFile().getAbsolutePath();
try {
Scanner input = new Scanner(Paths.get(fileName));
StringBuilder sb = new StringBuilder();
while(input.hasNextLine()) {
sb.append(input.nextLine()+ "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
finally {
input.close();
}
}//end readFile
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()== btnOpen) {
openFile();
}
}//end actionPerformed
}//end actionlistener
}//end class
Here is my last class, OutputPanel, this class contains the JTextArea:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputPanel extends JPanel{
public JTextArea txtOutput = new JTextArea(20,50);
public OutputPanel() {
add(txtOutput);
}//end constructor
}//end class
How do I get the textArea to display the contents of the file. More importantly why am I getting this exception and what can I do to fix it. Hopefully this makes as much sense as possible, and I really appreciate any and all input from you guys.
I used 'Thread' and 'TimeUnit' but not know how to use in the following program. I want when WIN+E execute then after some delay of 1 or 2 second next statement run. As, next statement is in for loop so it should run after 2 seconds infinite time (because of infinite for loop). You can see ActionListener line only.
package v;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class V extends JPanel{
private JButton V;
public V() throws AWTException{
Robot r = new Robot();
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
V = new JButton("PUSH");
add(V);
V.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
for (int i=0; i>0; i++) {r.keyPress(KeyEvent.VK_WINDOWS); r.keyPress(KeyEvent.VK_E); r.keyRelease(KeyEvent.VK_WINDOWS); r.keyRelease(KeyEvent.VK_E);}
}
});
}
public static void main(String[] args) throws AWTException {
V panel = new V();
JFrame frame = new JFrame ("V");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
i would go for something like this:
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class V extends JPanel{
private JButton V;
private boolean notstarted=true;
public V() throws AWTException{
Robot r = new Robot();
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
V = new JButton("PUSH");
add(V);
V.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
if(notstarted){
notstarted=false;
new Thread(new Runnable() {
#Override
public void run() {
while (true) {r.keyPress(KeyEvent.VK_WINDOWS);
r.keyPress(KeyEvent.VK_E);
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(StreamServer.class.getName()).log(Level.SEVERE, null, ex);
}
r.keyRelease(KeyEvent.VK_WINDOWS);
r.keyRelease(KeyEvent.VK_E);}
}
}).start();
}
}
});
}
public static void main(String[] args) throws AWTException {
V panel = new V();
JFrame frame = new JFrame ("V");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
As you can see i have added a boolean notstarted to control if the function have been accessed previously, so, this way you cant run that more than one and finally i have added a Thread to mitigate the impact the ActionListener could have on the thread that call it.
Anyway there should be beeter ways to achieve what you are looking for.
You can use javafx.animation.PauseTransition
PauseTransition happen = new PauseTransition(Duration.seconds(2));
happen.setOnFinished(e -> {
System.out.println("hello");
happen.playFromStart();
});
happen.play();
Like that. It will print hello every 2 seconds. That however requires you to extend javafx.application.Application and I see that you don't use javafx in your program.
You can use Thread.sleep as the other answer suggests - to sleep each 2000 miliseconds (in your loop).
There is also java.util.Timer and java.util.TimerTask. It allows you to do code every milisecond given in time. There is an excellent video of that here https://www.youtube.com/watch?v=36jbBSQd3eU
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Guiii extends JFrame{
private JButton menu;
private JButton custom;
public Guiii(){
super ("The Title");
setLayout(new FlowLayout());
menu = new JButton("menu Button");
add (menu);
Icon b = new ImageIcon (getClass().getResource("button.png"));
Icon x = new ImageIcon (getClass().getResource("greenbutton.png"));
custom = new JButton("Custom",b);
custom.setRolloverIcon(x);
add (custom);
HandlerClass handler = new HandlerClass();
menu.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("~s", event.getActionCommand()));
}
}
}
This is my code I am having some trouble and its not working, I have made a main for it but errors are showing can anyone help me and explain how the code will work khg
These are the errors
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at Guiii.<init>(Guiii.java:22)
at main.main(main.java:7)
This is the rest of the code but it had to be in another file:
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Guiii o = new Guiii();
o.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
o.setSize(300,200);
o.setVisible(true);
}
}
The constructor of the icon throws a NPE because getResource returns null.
Place the images in the same folder as the class Guiii.
I have a JFrame which contains a JPanel with the JButton "Press Me"
Pressing the "Press me" button will change to another JPanel(SecondPanel) within the same JFrame
I am facing a problem where there is a 10 second delay when i press the "Press Me" button before the SecondPanel appears.
This 10 second delay is caused the Timer event .
I wish for the SecondPanel to appear before the Timer event start.
What is happening now is that the Timer event starts , i am waiting at the "Press Me" button for 10 seconds , before the SecondPanel appears ,
can someone help me resolve this issue
Thanks
Main class used to run the project
package testing;
import java.io.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Testing extends JPanel
{
public static void main(String[] args)
{
frame = new JFrame();
LoginPanel lp = new LoginPanel();
frame.add(lp);
frame.pack();
frame.validate();
frame.setVisible(true);
}
static JFrame frame;
}
LoginPanel class
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginPanel extends JPanel
{
LoginPanel()
{
Loginbtn = new JButton("Press Me");
Loginbtn.addActionListener(new LoginButtonListener());
add(Loginbtn);
}
private class LoginButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
SecondPanel sp = new SecondPanel();
Utility.ChangePanel(sp);
sp.run();
}
}
JButton Loginbtn;
}
SecondPanel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SecondPanel extends JPanel
{
SecondPanel()
{
setLayout(new GridLayout(2,2));
//set deck image
File deckfile = new File("./src/testing/Ace_Club_1_1.png"); //deck image file location
try
{
Deckimg = ImageIO.read(deckfile); //read deck image
}
catch (IOException e)
{
}
Image scaledInstance = Deckimg.getScaledInstance(100, -1, Image.SCALE_SMOOTH);
DeckLabel = new JLabel(new ImageIcon(scaledInstance));
add(DeckLabel);
}
public void run()
{
Timer timer = new Timer(5000, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Code to be executed
System.out.println("HowareYou");
}
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!
try
{
Thread.sleep(7000);
}
catch(InterruptedException ie)
{
}
}
JLabel DeckLabel;
JPanel DeckPanel;
BufferedImage Deckimg;
}
Utility class used to switch JPanels within the JFrame
package testing;
import java.security.MessageDigest;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Utility
{
public static void ChangePanel(JPanel jp)
{
testing.Testing.frame.getContentPane().removeAll();
testing.Testing.frame.add(jp);
testing.Testing.frame.validate();
}
}
You're blocking the Swing event thread in SecondPanel.run() with Thread.sleep(7000). This will stop any GUI updates happening. If you remove the sleep you should see the second panel appear before the timer fires.