I have a general question about java. Because I want to create StronaGlowna.java (class) where I have place all buttons, check box and other GUI component which I want to display in main class. The first question is this right way, it's correct ? or maybe is better way to do this thing. My code look this:
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = -4575271483481196192L;
Container pane;
CardLayout layout;
public Main() throws FileNotFoundException, IOException {
layout = new CardLayout();
setLayout(layout);
pane = this.getContentPane();
/*Page: Strona główna */
JPanel newPanel = new JPanel();
pane.add("New", newPanel);
JButton przycisk = new JButton("Przycisk");
newPanel.add(przycisk);
...
In "pane.add("New", newPanel);" I want to display elements from:
package aplikacja.glowna;
import javax.swing.JButton;
import javax.swing.JPanel;
public class StronaGlowna {
public void StronaGlownaDisplay() {
JPanel newPanel = new JPanel();
JButton przycisk2 = new JButton("Przycisk");
newPanel.add(przycisk2);
}
}
Can I import/display all class StronaGlowna in main() something like a include in PHP ? What do You thing about my idea, it's correct or I'm wrong ? Thanks for help and discussion.
It sounds like the way Netbeans handling GUI. You may view the article in http://netbeans.org/kb/docs/java/quickstart-gui.html, it may help you understand how the GUI works since Netbeans can generate code for you. You can always import class and create object to access methods (often public methods) . I think it is not like a include in PHP. PHP include is like to directly include the source code, but jave is not.
First - Never, never, never, code in Main class. Call a method from it and then start your staff in another class. And, of course, don't extend it. And the constructor is neither a good idea. All of these are bad practices. Now, going into your problem, my suggestion is that you make StronaGlowna extend JPanel, and then obtain an instance of it through a public constructor, and use that instance as the parameter for the constructor of JScrollPane. That will make the scrollPane act as a 'screen' inside which you can see the contents of StronaGlowna, which is what I understand you're after.
Related
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.sound.midi.Patch;
import javax.swing.*;
this is were the code start
public class graficCar extends JComponent
{
private ImageIcon image1=null;
private JLabel label1=null;
private ImageIcon image2=null;
private JLabel label2=null;
graficCar(){
setLayout(new FlowLayout());
the problem here
image1=new ImageIcon(getClass().getResource("4596067.png"));
label1=new JLabel(image1);
add(label1);
}
the main
public static void main(String[] args)
{
graficCar g=new graficCar();
g.setDebugGraphicsOptions(JFrame.EXIT_ON_CLOSE);
g.setVisible(true);
}
As you mentioned, your png file is in C:\Users\user\Downloads folder. I bet class is somewhere else.
The problem is getResource() finds file in classpath by default. Here you could find details if you want to go deeper.
One solution is to put .png right next to your .java class but it's bad practice. More convenient way described here. The best practice is to create special folder for your resources in the project and then use relative path to it. How to do this is out of scope although it's described in many sites and in Stackoverflow too. Don't hesistate to use Search :)
Using Eclipse Mars, I copied a tiny Java program from the Internet that displays a small window containing a "Click me!" JButton and a JLabel. Every time you click the button, the label is updated to show the total number of clicks. Trying to learn about Java packages, I added this package statement at the top:
package nineteen_3;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String [] args {
...
}
}
This code worked fine.
Learned the trick of making a JButton that looks like a JLabel, Decided to make a package of new objects beginning with KLabel, a modified JButton.
package laobjects;
import javax.swing.JButton;
public class KLabel extends JButton {
...
}
No compile errors.
Back in Main {}, I added this import statement for KLabel. Below are existing import statements:
import laobjects.KLabel;
... and get: The import laobjects cannot be resolved
And in the Main {} code:
KLabel lbl = new KLabel("Count: 0");
I'm getting KLabel cannot be resolved to a type
Both the Package and Project Explorers show 'KLabel' as hi-level entries:
KLabel
src
laobjects
KLabel.java
KLabel
label
KLabel(String)
Like the in-built Math class, there are a couple of methods that one can use without importing the Math class. e.g
int io = (int) Math.random();
and notice the import region: no MATH whatsoever
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
but seeing, Math set doesn't have everything i needed, i created mine in a new class, but i can't seem to figure out what to do so i can be able to use it.
Taking a hint from the Math.java file, I've made my class final and my methods static but no avail..
Here's an excerpt of my code
package customops.Sets;
/**
*
* #author Kbluue
*/
public final class SetOpz {
public SetOpz(){}
public static int setMax(int[] set){
int out = set[0];
for(int i=1; i<set.length; i++){
out = Math.max(out, set[i]);
}
return out;
}
how do i use just the import command without having to copy and paste the SetOpz class in the DTL package?
You don't need to import Math explicitly because it is included by default. To use your own code you will have to import it. If you're using IntelliJ or Eclipse or some other smart IDE it will offer to import it for you automatically. Otherwise add a import statement at the top:
import customops.Sets.SetOpz;
You can import your method wherever you want to use with the following import statement
import static customops.Sets.SetOpz.setMax;
I'm a beginner in Java and I followed a tutorial to write this program (yes, I that much of a beginner) and it works perfectly when I run it on Eclipse. It also runs great on the computer I coded it on. However, if I send it to another computer (just the .jar file) and run it, it fails because it can't find the icon. Here is everything I've got. The icon I'm using is saved in the bin folder along with all the class files for the program. For privacy reasons, I replaced certain lines with "WORDS".
The tutorial I followed in two parts:
Part 1 - https://buckysroom.org/videos.php?cat=31&video=18027
Part 2 - https://buckysroom.org/videos.php?cat=31&video=18028
My main class (I called it apples cause the tutorial did).
import javax.swing.JFrame;
public class apples {
public static void main(String[] args) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(1920,1080);
go.setVisible(true);
}
}
And now my second class, "Gui":
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 custom;
public Gui () {
super("WORDS");
setLayout(new FlowLayout());
Icon b = new ImageIcon(getClass().getResource("b.png"));
custom = new JButton(null, b);
custom.setToolTipText("WORDS");
add(custom);
HandlerClass handler = new HandlerClass();
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
}
}
}
Thank you so much for helping!
It's worth reading Loading Images Using getResource where it's explained in detail along with loading images from jar as well.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("b.png"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/b.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/b.png"))
Read more...
I am storing some info in an ArrayList that is in a JPanel. I want to access this info from a JFrame so that I can print the contents of the ArrayList.
How do I do this?
This is what i have tried so far:
package projektarbete;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Spelet extends javax.swing.JPanel {
ArrayList<String> Resultat = new ArrayList<>();
.....
if(gameOver == true || vinst == true){
btnTillbakaTillMeny.setVisible(true);
int klick = antalKlick;
String namn = txfNamn.getText();
//Integer.toString(klick);
String klickString = klick+"";
String score = namn+"\t"+klickString;
Resultat.add(score);
That was the JPanel and the info is stored in the ArrayList called Restultat.
This is how I am trying to retrieve the info from the JFrame:
package projektarbete;
import javax.swing.JFrame;
public class Instruktioner extends javax.swing.JFrame {
//private final Meny Meny = new projektarbete.Meny();
private static void close() {
// throw new UnsupportedOperationException("Not supported yet.");
}
public Instruktioner() {
initComponents();
Spelet Resultat = new Spelet();
jTextArea1.setText(Resultat);
}
The thing is that NetBeans is underlining Resultat in jTextArea1.setText(Resultat);
Any ideas?
You cannot put a Resultat object as a parameter to setText(), because that method does not Accept a parameter of that type. If you look at the javadoc for the method, you will see what type(s) it takes (there may be more than one 'signature' for the method, each signature taking a different combination of types).
I think what you want to do is have a class and then an object that holds the data for your program. It will have the necessary methods for setting and obtaining data, and for calculating things that need calculation. Then, any object that is going to present information to the user (panel, frame, whatever) will need to have a reference to the class holding the data, and can call methods to get what it needs.
This is the very fundamental idea behind "model-view-controller" -- a *separation of concerns", where the logic for handling data is separated from the logic for displaying that data. It helps in the common cases where you need to change the presentation but the data handling itself is ok.
setText() is waiting for a string, but you gave it an ArrayList