I know this has been asked before...Just none of the answers on other questions worked.
When I try to run this in eclipse I just get Error: Could not find or load main class Hey.Init in the console. "Hey" is the package.
I can post the third class I just don't think it's relevant.
package Hey;
import javax.swing.SwingUtilities;
public class Init {
static Runnable createGui = new Runnable(){
public void run(){
new Gui();
}
};
public static void main(String[] args){
SwingUtilities.invokeLater(createGui);
}
}
Other Class:
package Hey;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gui {
private JFrame frame = new JFrame("Title");
private JButton button;
public Gui(){
frame.setLayout(new FlowLayout());
button = new JButton("DON'T HIT ME!!!");
button.addMouseListener(new Yo());
}
}
Weird as i do not see any issue in here. However it could be that you are trying to run a file which is not set as "main project" and effectively may not have a main method, if you know what i mean. Also on the side note
#Override
public void run(){
Gui gui = new Gui();
}
And one more thing why not implement the interface ?
public class Hello implements Runnable{
....
}
Related
I am going through thenewboston's tutorials and I have an unexpected error. I have tried to do everything that Eclipse suggest, but can't figure it out where the problem is.
this is my Main Class
import javax.swing.JFrame;
class Main {
public static void main(String args[]) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
}
and this is GUI Class
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 Gui extends JFrame {
private JButton reg;
private JButton custom;
public Gui(){
super("The title");
setLayout(new FlowLayout());
reg = new JButton("Regular Button");
add(reg);
Icon b = new ImageIcon(getClass().getResource("b.png"));
Icon a = new ImageIcon(getClass().getResource("a.png"));
custom = new JButton("Custom", b);
custom.setRolloverIcon(a);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
}
Thanks brothers for helping me out!
You've posted a couple of different stacktraces with the error on different line numbers but the code seems to have moved around. The error itself is talking about a NullPointerException in a constructor for ImageIcon. Not really anything to do with the JButton so the tags are misleading.
Basically you're looking up an image location of b.png and a.png. If these two files don't exist then you'll get a runtime exception like you have. The quick fix is to add these two images to the project so they are found.
A more robust solution would be to handle the exception and either output a more meaningful error or just carry on without the icon on the gui.
I've been making a battleship program that I've been trying to get working with a GUI, but it doesn't want to work. The way in theory it should work is that the GUI starts, it outputs a question to a box(which works), and then the computer waits and executes nothing until you press the button after you've answered your answer to the question. The problem is, my method that waits until you've clicked the button to fetch the data in the text field doesn't do anything. I've written a similar piece of code which demonstrates my problem below.
Test.java (main class)
package taest;
import javax.swing.*;
public class Test {
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
#SuppressWarnings("unused")
JFrame frame = new Frame();
}
});
Frame.display.setText(getButtonClick());
}
public static String getButtonClick(){
while(true){
if (Frame.hasClicked){
break;
}
}
return Frame.text.getText();
}
}
Frame.java (Frame class)
package taest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame extends JFrame{
JFrame panel = new JFrame("Something");
public static JTextArea text = new JTextArea();
JButton button = new JButton("Click");
public static JTextField display = new JTextField("NOthing");
static boolean hasClicked = false;
static String storage = "";
public Frame(){
setLayout(new BorderLayout());
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hasClicked = true;
storage = text.getText();
}
});
Container c = getContentPane();
c.add(display, BorderLayout.CENTER);
c.add(text, BorderLayout.PAGE_START);
c.add(button, BorderLayout.PAGE_END);
setVisible(true);
}
}
Static is not your friend and it's use should be greatly limited. It should NEVER be used to provide "easy" access to class fields for inter class communication
You need to turn the concept on it's head and possibly use some kind of Observer Pattern. This is where you have a class which is "observing" changes on your other class. When a change occurs the observed class notifies the observing class of the change. This decouples the responsibility as the observed class shouldn't care beyond notifying interested parties about something that happens
As a really primitive example...
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String args[]) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
#SuppressWarnings("unused")
JFrame frame = new Frame(new ViewController() {
#Override
public void messageChanged(View view, String msg) {
view.appendLog(msg);
}
});
}
});
}
public interface ViewController {
public void messageChanged(View view, String msg);
}
public interface View {
public void appendLog(String log);
}
public class Frame extends JFrame implements View {
// JFrame panel = new JFrame("Something");
private JTextArea text = new JTextArea(5, 5);
private JButton button = new JButton("Click");
private JTextField display = new JTextField("NOthing");
private String storage = "";
private ViewController viewController;
public Frame(ViewController controller) {
this.viewController = controller;
setLayout(new BorderLayout());
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
storage = text.getText();
viewController.messageChanged(Frame.this, storage);
}
});
System.out.println("display = " + display.hashCode());
System.out.println("text = " + text.hashCode());
Container c = getContentPane();
c.add(display, BorderLayout.CENTER);
c.add(text, BorderLayout.PAGE_START);
c.add(button, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void appendLog(String log) {
display.setText(log);
}
}
}
You should also become farmiluar within the concept of Model–view–controller
You are mixing things up,
First things first, the difference between Classes and Objects. A class is a blueprint for an object, so an example of a class is Car. The blueprint of such an object however knows nothing about the state of a particular instance of that class, lets assume that you drive 100 km/u, then you have an instance of Car that stores that it is going at 100 km/u. Blueprints are classes, Objects are instances.
So, public class Car makes an blueprint for cars, and new Car() makes a specific instance of that blueprint in which you can store runtime information.
Now there is a way to tell Java that things belong to the blueprint, static. If a variable is static it is attached to the blueprint. So to keep up with the analogy of cars, a static variable for a car can be its wheelbase, thats something that is defined at compiletime (or in the car analogy at create time).
Back to your problem, you are mixing up classes and objects, what you want to do is have a BattleshipWindow of which instances exist. Of this BattleshipWindow an instance can be created with new, and then its properties can be changed.
Not exactly the answer you want probably, but I hope you now understand the difference between classes and objects, that will help you solve your problem.
I've tried to make it work, am I missing a code to make it be able to show the gui on windows,
or do I need some kind of Java to run it?
Here is my code:
package math;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame window = new JFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Your code compiles and runs fine. (Although it is more appropriate to put setVisible command in the initialize method).
Seems like you could not export it properly. I exported your code with NetBenas and I could run it by double clicking on it. Try exporting your class with NetBenas (It makes it easier).
If you dont have NetBeans and creating the jar file via command line check your manifest file. Make sure you gave the correct main method name.
the Main window part doesn't make sense
replace your try-block
try {
Main window = new Main();
window.frame.setVisible(true);
}
with
try {
initialize();
frame.setVisible(true);
}
you have to set your frame visible in contructor.
private void initialize() {
frame = new JFrame();
frame.setVisible(true);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
The code above works fine. It could be that it worked for you but you didn't realize because the window created is very small. It could also be that you tried to export this into a .jar file but didn't specify in the Manifest what the Main-Class should be. Depending on the IDE or build tool that you're using, the way might be different. It could also be that you simply do not yet know how to get this code running at all, i.e. compiling and running Java code. In that case, you need to learn about javac and java, which are included in the Java SDK.
If you use Java 8, you could actually simplify the code. You don't need an exception handler that prints the stack trace, the EventQueue is already doing that for you.
package math;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame window = new JFrame();
window.setVisible(true);
});
}
}
or, if the code is in a separate method:
package math;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(Main::initUI);
}
private static void initUI() {
JFrame window = new JFrame();
window.setVisible(true);
}
}
If initUI() is to be an instance method, you could do it like this:
package math;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
new Main();
}
Main() {
EventQueue.invokeLater(this::initUI);
}
private void initUI() {
JFrame window = new JFrame();
window.setVisible(true);
}
}
So I have 3 JFrames. JFrame 1 (aka opts) is for inputting some variables. On OK, it creates JFrame 2 (aka view, a graphical viewing Frame). In the constructor, JFrame 3 (aka manager, for cycling through the graphical views) is created instantly.
I want them to be Windows-alike decorated with JFrame.setDefaultLookAndFeelDecorated(true) (from now on referred to as "it").
A few differtent cases:
When I don't set it at all, all JFrames are Windows decorated.
When I put it in the "opts" or "manager" constructor, run the project, and click the OK button, all JFrames are Windows-alike decorated.
However, when I put it in the "view" constructor, only "opts" and "view" are Windows decorated, but "manager" is Java decorated.
But when I put it in a class which does nothing more than read some data from a file, and make some objects out of it, only "opts" is Windows decorated.
How exactly does it work? I want to know why it happens as it happens.
Edit: I can't reproduct case 4, but still, some things happen that I don't understand. Try commenting out some of the "it"s. It'll give some strange results.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame1 extends JFrame {
public Frame1() {
JFrame.setDefaultLookAndFeelDecorated(true);
Frame1.setOptions(this);
JButton b1 = new JButton("hi");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
makeFrame2(2);
}
});
this.add(b1);
}
public void makeFrame2(int x) {
this.dispose();
new Frame2(x);
}
public static void setOptions(JFrame f) {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250, 250);
f.setEnabled(true);
f.setVisible(true);
}
public static void main(String[] args) {
new Frame1();
}
}
package test;
import javax.swing.JFrame;
public class Frame3 extends JFrame {
Frame2 link;
SomeClass sc;
public Frame3(Frame2 link) {
JFrame.setDefaultLookAndFeelDecorated(true);
Frame1.setOptions(this);
this.link = link;
sc = new SomeClass(25);
}
}
package test;
import javax.swing.JFrame;
public class SomeClass {
int x;
public SomeClass(int x) {
JFrame.setDefaultLookAndFeelDecorated(true);
this.x = x;
}
}
package test;
import javax.swing.JFrame;
public class Frame2 extends JFrame {
public Frame2(int x) {
JFrame.setDefaultLookAndFeelDecorated(true);
Frame1.setOptions(this);
new Frame3(this);
}
}
According to the oracle java documentation, setDefaultLookAndFeelDecorated changes the parameter for all newly created JFrames, all existing JFrames are unchanged.
JFrame Documentation
I've been programming in Java for a little while now but have never really done much with the swing packages. I am currently designing a GUI for an A.I. call and response program despite the relative complexity (for me at least) of the rest of what I have been doing, this image loading problem, which seemed extremely simple to implement is stumping me.
The below classes work if not in a package, which is what really confuses me. I've tried several different implementation suggestions (one from Head First Java, one from the docs.oracle.com tutorials and another using what http://leepoint.net/notes-java/GUI-lowlevel/graphics/45imageicon.html suggests).
package CaRII;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class P{
public static void main(String [] args){
P p = new P();
p.go();
}
public void go(){
JFrame frame = new JFrame("CaRRI: Call and Response Intelligent Improviser");
PBackground mainPanel = new PBackground();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(800,500);
frame.setVisible(true);
}
}
package CaRII;
import java.awt.*;
import javax.swing.*;
public class PBackground extends JPanel{
public Image backgroundImage;
public PBackground(){
backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg");
}
public PBackground(LayoutManager layout){
backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg");
}
public void paint(Graphics g){
g.drawImage(backgroundImage,0,0,null);
}
}
Like I said the strange thing is that it doesn't display the image if these two classes are in package CaRRI; but if I compile and run them without the package declaration they run fine(albiet the image not loading until the window resizes... but i have seen solutions online for that so I will be able to sort that once I get it loading within the package). I have been writing in XCode and JEdit and the image is stored within the package folder inside source (/src/CaRII/P.java ... /src/CaRII/CaRIIBackGround.jpg), I have also tried storing the image in a resources folder within /src/ and using
ImageIcon(getClass().getResource("/resources/CaRIIBackGround.jpg)).getImage();
but that that causes another error when run
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at CaRII.PBackground.<init>(PBackground.java:19)
at CaRII.P.go(P.java:21)
at CaRII.P.main(P.java:15)
Any help would be much appreciated as despite its simplicity this has been stumping me all morning and I have a lot of other classes to write.
Thanks
(Heres the image(im a new user so i cant post images but this is a link to it))
http://imageshack.us/photo/my-images/189/cariibackground.jpg
package CaRII;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class P{
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
P p = new P();
p.go();
}
});
}
public void go(){
try {
JFrame frame = new JFrame("CaRRI: Call and Response Intelligent Improviser");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
PBackground mainPanel = new PBackground();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
//frame.setSize(800,500);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch(Exception e) {
e.printStackTrace();
}
}
}
class PBackground extends JPanel{
public BufferedImage backgroundImage;
public PBackground() throws Exception {
URL url = new URL("http://desmond.imageshack.us/Himg189/" +
"scaled.php?server=189&filename=cariibackground.jpg&res=medium");
// You might form that URL using something like..
//URL url = this.getClass().getResource("/CaRIIBackGround.jpg");
backgroundImage = ImageIO.read(url);
Dimension d = new Dimension(
backgroundImage.getWidth(),
backgroundImage.getHeight());
setPreferredSize(d);
}
/* What was this supposed to achieve?
public PBackground(LayoutManager layout){
backgroundImage = Toolkit.getDefaultToolkit().createImage("CaRIIBackGround.jpg");
}
*/
// Don't override paint() in a Swing panel!
//public void paint(Graphics g){
#Override
public void paintComponent(Graphics g) {
// USE the ImageObserver!
//g.drawImage(backgroundImage,0,0,null);
g.drawImage(backgroundImage,0,0,getWidth(),getHeight(),this);
}
}
This code works for me :
package CaRII;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class PBackground extends JPanel{
public Image backgroundImage;
public PBackground(){
super();
initImage();
}
private void initImage() {
backgroundImage = new ImageIcon(getClass().getResource("/resources/cariibackground.jpg")).getImage();
}
public PBackground(LayoutManager layout){
super(layout);
initImage();
}
#Override
public void paint(Graphics g){
g.drawImage(backgroundImage,0,0,null);
}
}
But be carefull I've got the same error (Exception in thread "main" java.lang.NullPointerException) than you when I generate my jar file because of Upper case in the image name. You should use only lower case names for your resources if you use windows.
Regards,
Check this Link out, this has to be your Directory Structure, for placing Images, Do check the code example too. MY PROJECT. I just created this project for you to know, how things need to be, to be accessed, if you doing that manually.