What could be the problem here why the static method doesn't print components names of components in a JPanel?
import java.awt.Component;
import java.awt.Window;
import javax.swing.*;
public class Users {
public static void saveUpdate(JPanel pnlUsers)
{
Component[] components = pnlUsers.getComponents();
for(int i=0;i<components.length;i++){
System.out.println("Component name - " + components[i].getName());
// For database update. Code will be added after fix.
}
}
}
components[i].getName() always returns null instead of the componenet's name.
Related
I am trying to make a functionality for quick search of clients from database on some keystrokes from user, using an editable combobox. What i wanted to have is, user will put in some letters and if those lettters match with some clients, those clients will be remained in the current data model of the combobox.
The code is as follows.
Please fix the exception occuring in the code. Thanks in Advance !!
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalStateException: Attempt to mutate in notification
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
class ComboSearch extends JFrame implements CaretListener
{
private JComboBox mycombo;
private ArrayList<String> list;
private DefaultComboBoxModel<String> isolatemodel,model;
public ComboSearch()
{
setSize(400, 400);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
mycombo=new JComboBox();
mycombo.setEditable(true);
mycombo.setBounds(30,30, 350, 50);
isolatemodel=new DefaultComboBoxModel();
model=new DefaultComboBoxModel();
list=new ArrayList();
add(mycombo);
mycombo.setModel(isolatemodel);
((JTextField)mycombo.getEditor()
.getEditorComponent()).addCaretListener(this);
setVisible(true);}
private void addElements()
{
list.add("Rambhau, Vijay Nagar");
list.add("Surya, Ashok Puri");
list.add("Mourya, Shahjapur");
list.add("Kishorji & sons, Bhopal");
list.add("Fablica & jewels, Itanagar");
list.add("Guru Kripa,Ujjain");
list.add("Hariram Nai & Bakes, Indore");
list.add("Ganesh Sev Bhandar, Harda");
list.add("Greatsome Higs, Jabalpur");
list.add("Treks and hains, Nalanda");
list.add("Tata Indora, Hoshangabad");
list.add("Paankhai Seth, Madurai");
list.add("Katappa, Shikara");
list.add("Gunjan Samosa, Vijay Nagar");
list.add("Ramesh hustlers , Vijay Nagar");
}
public void makeModels()
{
addElements();
list.stream().forEach((client) -> {
isolatemodel.addElement(client);
});
}
#Override
public void caretUpdate(CaretEvent e)
{
String searchText=((JTextField)mycombo.getEditor()
.getEditorComponent()).getText();
if(!searchText.isEmpty())
{
for(int i=0; i<isolatemodel.getSize();i++)
{
if(isolatemodel.getElementAt(i).contains(searchText))
{
model.removeAllElements();
model.addElement(isolatemodel.getElementAt(i));
}
}
mycombo.setModel(model);
mycombo.showPopup();
}
else
{
mycombo.setModel(isolatemodel);
}
}
}
public class Execute
{
public static void main(String[] args)
{
ComboSearch searchIt=new ComboSearch();
searchIt.makeModels();
}
}
model.removeAllElements();
model.addElement(isolatemodel.getElementAt(i));
and if those lettters match with some clients, those clients will be remained in the current data model
Well, then it doesn't make sense to remove all the items every time you find a match. Then you will only ever have one entry left in the combo box.
You need to remove all the items BEFORE you start your loop processing and then just add back in the elements that match.
IllegalStateException:
You are trying to update the combo box model before processing of the typed event has finished processing.
Wrap the code in the listener in a SwingUtiltities.invokeLater(...) to the code will be executed after all processing has been finished.
Also, you would generally use a DocuementListener to be notified when the text of the editor has changed, not a CaretListener. The user could use the arrow keys to move the caret so there is no need to update the model in that case.
I have the following question: I am trying to execute the usConstitution wordcram example (code follows) and if provided as is the code executes in eclipse, the applet starts and the word cloud is created. (code follows)
import processing.core.*;
//import processing.xml.*;
import wordcram.*;
import wordcram.text.*;
import java.applet.*;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.awt.event.FocusEvent;
import java.awt.Image;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.zip.*;
import java.util.regex.*;
public class usConstitution extends PApplet {
/*
US Constitution text from http://www.usconstitution.net/const.txt
Liberation Serif font from RedHat: https://www.redhat.com/promo/fonts/
*/
WordCram wordCram;
public void setup() {
size(800, 600);
background(255);
colorMode(HSB);
initWordCram();
}
public void initWordCram() {
wordCram = new WordCram(this)
.fromTextFile("http://www.usconstitution.net/const.txt")
.withFont(createFont("https://www.redhat.com/promo/fonts/", 1))
.sizedByWeight(10, 90)
.withColors(color(0, 250, 200), color(30), color(170, 230, 200));
}
public void draw() {
if (wordCram.hasMore()) {
wordCram.drawNext();
}
}
public void mouseClicked() {
background(255);
initWordCram();
}
static public void main(String args[]) {
PApplet.main(new String[] { "--bgcolor=#ECE9D8", "usConstitution" });
}
}
My problem is the following:
I want to pass through main (which is the only static class) an argument so as to call the usConstitution.class from another class providing whichever valid filename I want in order to produce its word cloud. So how do I do that? I tried calling usConstitution.main providing some args but when I try to simply print the string I just passed to main (just to check if it is passed) I get nothing on the screen. So the question is How can I pass an argument to this code to customize .fromTextFile inside initWordCram ?
Thank you a lot!
from: https://wordcram.wordpress.com/2010/09/09/get-acquainted-with-wordcram/ :
Daniel Bernier says:
June 11, 2013 at 1:13 am
You can’t pass command-line args directly to WordCram, because it has no executable.
But you can make an executable wrapper (base it on the IDE examples that come with WordCram), and it can read command-line args & pass them to WordCram as needed.
FYI, it’ll still pop up an Applet somewhere – AFAIK, you can’t really run Processing “headless.” But that’s usually only a concern if you’re trying to run on a server.
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
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.