I was creating a program to work with a drop-down list, but I got stuck at the line of declaration of JComboBox box, I get these error messages:
Multiple markers at this line
- The constructor JComboBox(String[]) is
undefined
- Line breakpoint:JComboBox [line: 25] -
JComboBox()
No matter how I try to define JComboBox, I get some sort of error. Please help me with it.
Here's the code of the public class:
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class JComboBox extends JFrame {
private JComboBox box;
private JLabel picture;
private static String[] filename = { "p.png", "i.png" };
private Icon pics[] = { new ImageIcon(getClass().getResource(filename[0])),
new ImageIcon(getClass().getResource(filename[1])) };
public JComboBox() {
super("This is the title");
setLayout(new FlowLayout());
JComboBox box = new JComboBox(filename);
box.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
});
add(box);
picture = new JLabel(pics[0]);
add(picture);
}
}
And here's the code of the main class:
import javax.swing.*;
public class JComboBox1 extends JFrame {
public static void main(String[] args) {
JComboBox Box = new JComboBox();
Box.setVisible(true);
Box.setSize(400,400);
Box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Thank you.
Your problem, as #Andy mentioned is that you have a collision in the name of your class and the swing component. If you absolutely must name your class JComboBox you'll have to reference the swing component by the fully-qualified name, as such
public class JComboBox extends JFrame {
private javax.swing.JComboBox box;
If you hover over your private instance with an IDE you should see the fully-qualified name matching the package in which you've created your JComboBox class. Save yourself some pain and rename your class.
Related
My question is about an error message I don't understand. Well.. I do understand what it says, but not why it says so or how to fix it. I just started the learning chapter about Swing, and this is one of the examples in my course. I copy/pasted every word into Netbeans but for some reason, it doesn't work.
I have a class called MijnVenster (meaning "MyWindow"), where a JPanel is created with some JButtons with an ActionListener. In the class, there are 2 inner classes describing the performed action.
There's an error message next to both class headers,, saying:
MijnVenster.HoofdLetterListener is not abstract and does not override abstract method actionPerformed (ActionEvent in ActionList)
The other error message next to both #Override statements says:
method does not override or implement a method from a supertype
Isn't that exactly what I did?
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class MijnVenster extends JFrame {
private static final long serialVersionUID = 1L;
private final static String ZIN = "Hier staat een zin";
private final JTextField textField = new JTextField(ZIN);
public MijnVenster() {
super("Letters");
add(textField);
JPanel panelSouth = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton buttonHoofdLetters = new JButton("Hoofdletters");
panelSouth.add(buttonHoofdLetters);
JButton buttonKleineLetters = new JButton("Kleine letters");
panelSouth.add(buttonKleineLetters);
add(panelSouth, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonHoofdLetters.addActionListener(new HoofdLetterListener());
buttonKleineLetters.addActionListener(new KleineLettersListener());
}
// an inner class for upper case
private class HoofdLetterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
textField.setText(ZIN.toUpperCase());
}
}
// an inner class for lower case
private class KleineLettersListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
textField.setText(ZIN.toLowerCase());
}
}
}
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.
The Question
Create a new project in Eclipse
• Create a JFrame application that contains ONE JButton with the label “List All Locales” and ONE JTextArea. Output ALL available Locales to the JTextArea when the JButton is pushed.
So I have the code working where it has the JButton but I can't seem to get it printing out all the Locales in the JTextArea when the button is pressed. Is there something I'm missing
My Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
*/
/**
* #author Michelle
*
*/
public class Exercise1 extends JFrame implements ActionListener{
JButton button;
JFrame frame;
JTextArea ta;
private static final long serialVersionUID = 1L;
Locale[] available = Calendar.getAvailableLocales();
public Exercise1(){
Container c = getContentPane();
JPanel p = new JPanel();
ta = new JTextArea(20,22);
ta.setText("All Locales will display here");
ta.setEditable(false);
button = new JButton();
button.setText("List all Locales");
JScrollPane output = new JScrollPane(ta);
button.addActionListener(this);
p.add(button, BorderLayout.SOUTH);
p.add(output);
c.add(p);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
// TO DO Auto-generated method stub
if (a.getActionCommand().equals("List All Locales")){
for(int i=0; i<available.length;i++){
ta.append(available[i].getDisplayName()+"\n");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Exercise1 myLocaleTest = new Exercise1();
myLocaleTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The text on the button says "List all Locales"
button.setText("List all Locales");
In actionPerformed, you're checking if the action command is "List All Locales"
if (a.getActionCommand().equals("List All Locales")){
Do you see the difference between "List all Locales" and "List All Locales"?
To avoid this kind of mistake, you could create a constant in your class, and use that. For example:
public class Exercise1 extends JFrame implements ActionListener{
private static final String BUTTON_ACTION = "List all Locales";
public Exercise1(){
// ...
button.setText(BUTTON_ACTION);
// ...
}
public void actionPerformed(ActionEvent a) {
if (a.getActionCommand().equals(BUTTON_ACTION)){
// ...
Change to equalsIgnoreCase instead...
if (a.getActionCommand().equalsIgnoreCase("List all locales")){
Misspelling here if (a.getActionCommand().equals("List All Locales")). Button have next command "List all Locales". Change that and all will be work.
Others have already pointed out that your string check has an upper/lower case typo in it.
The suggestion to use a static final is good, but NOT for the button label! Why? Zero language support!
I did a quick search online and found the method: setActionCommand(String);
private static final String ACTION_COMMAND = "ac1";
...
JButton jbutton = new JButton();
jbutton.setText("My label text");
jbutton.setActionCommand(ACTION_COMMAND);
...
if ( action.getActionCommand().equals(ACTION_COMMAND) )
The static final should be used for setting the action command and for testing for the action, but not the label!
I am pretty new to Swing, any help appreciated.
I have the following situation:
A "Main" Class where I define my main JPanel and default Label text.
A "GUILabel" Class (extends JLabel) where I define the look of the Text Labels.
A "popupmenu" Class (extends JPopupMenu) where I define the content of the popupmenu.
Target:
When I right-click on a panel the popupMenu should appear (this already works).
When I choose a menu item of this popupMenu, the text of the label I clicked on should change.
I guess its currently not working (I am sorry this code isn't complete - this is my 5th attempt), because I create the popup menu Once in the Main Class. Then I am adding this popup menu to each Label. So I guess thats why getInvoker() returns null in the popup menu class.
But do I really have to create a new popupmenu for each JLabel? Cant this single menu just handle all Components assigned to?
Main Frame:
package popupshit;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.border.BevelBorder;
public class Model implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 3));
frame.setVisible(true);
GUIPopupMenu popup = new GUIPopupMenu(9);
JLabel label1 = new GUILabel();
label1.setComponentPopupMenu(popup);
JLabel label2 = new GUILabel();
label2.setComponentPopupMenu(popup);
JLabel label3 = new GUILabel();
label3.setComponentPopupMenu(popup);
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent e) {
((JLabel) e.getSource()).setText("" + e.getActionCommand());
}
}
PopupMenu:
package popupshit;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class GUIPopupMenu extends JPopupMenu {
public GUIPopupMenu(int numbers) {
for (int i = 1; i < numbers; i++) {
JMenuItem popMenuItem = new JMenuItem("" + i);
popMenuItem.addActionListener ((ActionListener) this.getInvoker());
System.out.println(this.getParent());
this.add(new JMenuItem("" + i));
}
this.addSeparator();
this.add(new JMenuItem("remove"));
}
}
GUILabel:
package popupshit;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.BevelBorder;
public class GUILabel extends JLabel implements ActionListener {
public GUILabel() {
this.setBorder(new BevelBorder(BevelBorder.LOWERED));
this.setVisible(true);
this.setPreferredSize(new Dimension(50, 50));
this.setText("0");
}
#Override
public void actionPerformed(ActionEvent e) {
this.setText((String) e.getActionCommand());
JOptionPane.showMessageDialog(null, "worked!" );
}
}
invoker is null because until the popup menu is a actually invoked, it has no invoker.
Instead, add a simple ActionListener to the menu item which, when invoked, uses the invoker property to determine which should occur.
My personal preference would be to create a new instance of the popup menu for each component separately, passing a reference of the component in question or some other controller as required...but that's me...
Add an ActionListener to the menu item something like:
#Override
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
JPopupMenu popup = (JPopupMenu)c.getParent();
JLabel label = (JLabel)popup.getInvoker();
...
}
Don't extend JPopupMenu just to add a few menu items to the popup.
Ok guys, I've made some changes in my code as told by you. I have 3 classes:
The second class (and first GUI): I have 4 JButtons - Simulare, CazParticular, Start and HandSelection, some JLabels and 3 JTextFields; When I press the HandSelection button another frame it's created with different content.
The 3rd class (and second GUI): I have 2 JButtons - Ok and Cancel and other stuff. When I press the Ok button I want to the access to the JTextField(QuesHandText) from the first Gui and use the method setText(). I can't figure this out, I'm thinking on this like 4-5 days and still can't get the answer. Please help me!
What code should I write in if statement to be able to modify the text in the JTextField from 2nd class (first GUI) ?
First class:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
//other stuff
GuiMain gui = new GuiMain();
gui.frame1.setLocation(150,150);
gui.frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.frame1.setSize(400,250);
gui.frame1.setResizable(false);
gui.frame1.setVisible(true);
//other stuff
}
}
Second class:
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class GuiMain {
public static GuiMain instance;
public static GuiMain getInstance(){
if(GuiMain.instance == null){GuiMain.instance = new GuiMain();}
return GuiMain.instance;
}
public JFrame frame1 = new JFrame();
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public JButton Simulare, CazParticular, Start, HandSelection;
public int w1,h1;
public JLabel someText;
static int u=0;
public int j=0;
public GuiMain(){
frame1.setTitle("HoldemTool");
frame1.setLayout(null);
QuesHandText = new JTextField(4);
Simulare = new JButton("Simulare");
CazParticular = new JButton("Caz particular");
Start = new JButton("Start");
HandSelection = new JButton(new ImageIcon(getClass().getResource("GuiPic.png")));
Handler handler1 = new Handler();
CazParticular.addActionListener(handler1);
Simulare.addActionListener(handler1);
HandSelection.addActionListener(handler1);
Start.addActionListener(handler1);
QuesHandText.setEditable(false);
FlopTurnRiverText.setEditable(false);
RezultatText.setEditable(false);
frame1.add(Welcome1);
frame1.add(Welcome2);
frame1.add(QuesHand);
frame1.add(FlopTurnRiver);
frame1.add(Rezultat);
frame1.add(QuesHandText);
frame1.add(FlopTurnRiverText);
frame1.add(RezultatText);
frame1.add(Simulare);
frame1.add(CazParticular);
frame1.add(Start);
}
public JTextField getQuesHandText(){
return QuesHandText;
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==Simulare)
{
}
if(e.getSource()==CazParticular){
QuesHandText.setEditable(true);
FlopTurnRiverText.setEditable(true);
QuesHandText.setText("");
FlopTurnRiverText.setText("");
RezultatText.setText("");
frame1.setSize(470, 250);
Start.setBounds(3*FlopTurnRiverText.getX(), QuesHand.getY(), 65, h1);
HandSelection.setBounds(3*FlopTurnRiverText.getX(), FlopTurnRiverText.getY(), 65, h1);
frame1.add(HandSelection);
frame1.add(Start);
}
if(e.getSource()==Start){
QuesHandText.setText("Text");
}
if(e.getSource()==HandSelection){
GuiSelection gui2 = new GuiSelection();
gui2.frame2.setVisible(true);
}
}
}}
3rd class
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class GuiSelection extends GuiMain {
JFrame frame2 = new JFrame();
GuiMain guiMain;
public JButton Ok,Cancel;
//other stuff
public GuiSelection(){
guiMain = new GuiMain();
frame2.setTitle("Hand selection");
frame2.setSize(1135,535);
frame2.setLayout(null);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
frame2.setResizable(false);
//other stuff
Handler2 handler2 = new Handler2();
Ok.addActionListener(handler2);
Cancel.addActionListener(handler2);
frame2.add(Ok); frame2.add(Cancel);
}
public class Handler2 implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==Cancel){
frame2.hide();
}
if(e.getSource()==Ok)
{
GuiMain.getInstance().getQuesHandText().setText("From Ok");
//When I prees this button "Ok" I want to get access to the JTextField(QuesHandText) in the GuiMain class, and .setText();
//somothing like QuesHandtText.setText("someText");
}
}
}
}
Add to your first GUI the method public JTextField getQuesHandText() and a static method public static JFrame getInstance() which returns the instance of the first GUI. Now you can call SecondClass.getInstance().getQuesHandText() from anywhere to get the JTextField instance. Note that with this method you can only have a single instance of SecondClass at any time.
Your getInstance() method will look as follows:
public class SecondClass extends JFrame {
private static SecondClass instance;
public static SecondClass getInstance() {
if(SecondClass.instance == null)
SecondClass.instance = new SecondClass();
return SecondClass.instance
}
}
Note that you shouldn't create an instance of SecondClass manually.
Use Composition,
1. Create the instance of the class which contains the JFrame, whose JTextField you need to access.
2. Then on that instance call the setter or getter method of the JTextField.
Edited:
Make Sure you have implemented Singleton principle on the Main class, else you will get
a new instance , which you dont want......
In Second class.
public class GuiMain{
Main m = new Main();
m.getText();
m.setText();
// Other stuffs
}
Perhaps you do not really need two Windows. What you need is a Dialog which can be achieved by the class JOptionPane.
Here is a demo code.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class YourGui implements ActionListener {
private JFrame frame;
private JTextField text;
private JButton takeInput;
public YourGui() {
frame = new JFrame();
frame.setLayout(new GridLayout(2, 1));
text = new JTextField();
takeInput = new JButton("Take Input!");
frame.add(text);
frame.add(takeInput);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
takeInput.addActionListener(this);
}
public void show() {
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
int selection =
JOptionPane.showConfirmDialog(frame, "Select Hand", "Select",
JOptionPane.OK_CANCEL_OPTION);
if (selection == JOptionPane.OK_OPTION) {
text.setText("You selected ok");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
YourGui gui = new YourGui();
gui.show();
}
});
}
}
Use the instance of the initiated Class to get access to its public variables. So you should do something like:
GuiMain main=new GuiMain();
...
main.QuesHandtText.setText("someText");
Alternatively if your JTextField is private (though its not) use an instance method that has public access to change its contents - this is the preferred method:
Class A:
class A {
private JTextField tf;
public void setFieldText(String text) {
tf.setText(text);
}
}
Class B:
class B {
A a = new A();
a.setText("hello");
}
In the handler of GuiMain, pass itself (the main JFrame) as an argument to the constructor of GuiSelection:
GuiSelection gui2 = new GuiSelection(this);
And then change the constructor of GuiSelection from
public GuiSelection(){
guiMain = new GuiMain();
...
to
public GuiSelection(GuiMain guiMain){
this.guiMain = guiMain;
...
Also, it seems quite odd that GuiSelection is a subclass of GuiMain. Probably both of these should be direct subclasses of JFrame.
Also, you should wrap everything in the main method within SwingUtilities.invokeLater since everything related to Swing should run on the event-dispatch thread.
Also, you should never use public member variables: it is very un-Java.