This question already has answers here:
Java throwing error "<Class Name> is not abstract and does not override abstract method in the <Interface>"
(3 answers)
Closed 6 years ago.
I'm trying to implement ActionListener so that my GenderIsStored method of my GenderGUI class can record the number of times a user selects each JRadioButton that represents a gender, with each iteration of the loop in the driver class of my program. However, I cannot get my GenderGUI class to compile properly, due to the fact that I cannot figure out how to override the abstract method. The GenderCount class is implementing the ActionListener interface, which is abstract. Originally, I thought that in order to compile correctly, I would have to implement all the methods inside the parent interface (which is ActionListener), but the same problem occurred. Does anyone know how I can solve this problem?
public GenderGUI()
{
GenderChoice = new JLabel ("Select your gender below: ");
Male = new JRadioButton ("Male");
Female = new JRadioButton ("Female");
ButtonGroup GenderGroup = new ButtonGroup();
GenderGroup.add (Male);
GenderGroup.add (Female);
GenderCount listener = new GenderCount ();
Male.addActionListener (listener);
Female.addActionListener (listener);
primary = new JPanel();
primary.add (GenderChoice);
primary.add (Male);
primary.add (Female);
}
public JPanel getGenderPanel()
{
return primary;
}
private class GenderCount implements ActionListener
{
public void GenderIsStored (ActionEvent event)
{
Object source = event.getSource();
if (Male.isSelected())
{
MaleCount++;
}
else
FemaleCount++;
}
}
}
Your GenderCount clearly doesn't implement ActionListener.
You need anactionPerformed(). Actually looks like you have one, but you have given it the wrong name: GenderIsStored instead of actionPerformed
Related
I have an A class and a B class
In the A class I have multiple B instances. From A class, after defining B, I write a mouseListener event for the B class, and it works. Now I realiced that I have to write the same mouseListener for every B class that I instantiate, and all they do is the same: Opening a DialogBox asking for a number, so I decided to write that mouseListener in the B class constructor.
The problem comes when that mouseListener has to access to an A's private attribute. In this point, I thought about using a functional interface / callback to send values from B to A when the mouseEvent is fired, but I feel like the code will be a little bit messy, like I'm using the wrong tools to reach the functionality I want, maybe I'm wrong...
Any advice or recomendation ? I'll post a little bit of the code so you can understand it better. This is my A class: This code works but now think that I have to write the same code lines again and again
PowerConfigPanel is the A class.
PTextField is the B class.
connectionListener is the A private attribute I was talking about.
public class PowerConfigPanel extends JPanel {
private ConnectionListener connectionListener;
public PowerConfigPanel(){
PTextField SUSPEND_CHARGER_BF= new PTextField(7);
SUSPEND_CHARGER_BF.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
JPanel insertValuePanel = new JPanel();
insertValuePanel.setLayout(new GridLayout(3,2,1,1));
PTextField field = new PTextField(7);
insertValuePanel.add(UtilsService.createComponentPanel(field,"Insert Value "));
int result = JOptionPane.showConfirmDialog(null, insertValuePanel,
"Please Enter a new Value", JOptionPane.OK_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
JOptionPane.showMessageDialog(null, "Invalid input for seconds", "Error", JOptionPane.ERROR_MESSAGE);
connectionListener.connect("a","b",Integer.valueOf(field.getText()));
}
}
});
}
}
What I mean is: mouseClick returns void... is there any possibility to make it return an integer and collect that integer in the A class when the B class is clicked?
What I want to achieve is very simple.
I have 2 classes. "SpeedingTicket" & "SpeedingTicket GUI".
Inside my GUI I have 1 textbox name txtSpeedLimit & a button.
Inside my SpeedingTicket class I have a variable "int speedingTicket".
Inside my SpeedingTicket class I also have a get & set method for "speedingTicket".
I know how to get and set text using JTextFields, but I want to be able to:
receive input from the "txtSpeedLimit", and store that value into the "txtSpeedLimit" instance variable in the "SpeedTicket" class. I can then check for validation etc when I come to adding the vehicle speed.
Maybe this isn't the most efficient way of dealing with this program. Maybe I should scrap the instance variables in SpeedingTicket, and deal with it all in the GUI.
Any advice would be hugely appreciated.
Basically what I'm trying to do is this:
class confirmHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String val = txtSpeedLimit.getText();
int realNum = speed.getSpeedLimit() = txtSpeedLimit; < but obviously that doesn't work, but I want the textbox link to the variable.
EDIT: If we take away the GUI, all I want my program to do is the following:
Speed Limit: 50 < enterd via textfield
Speed: 60 < entered via textfield
if the speed is blah blah (ive already coded this).. then output a result to one of my labels.
I achieved this without making a GUI and making it only console based, but instead of the user typing it via the console, I want it to be typed via textfields.
THe values that are entered into the textfields should be stored in the two variables (speed and speedlimit) that are in the SpeedingTicket class.
You can update a value in:
public class SpeedingTicket {
int speedingTicket;
public SpeedingTicket() {
speedingTicket = 500;
}
public int getSpeedingTicket() {
return speedingTicket;
}
}
by:
public class SpeedingTicketGUI extends JPanel{
SpeedingTicket st;
SpeedingTicketGUI() {
st = new SpeedingTicket();
setLayout(new FlowLayout(FlowLayout.LEFT));
JTextField txtField = new JTextField(10);
txtField.setText(""+st.getSpeedingTicket());
add(txtField);
JButton btn = new JButton("Update");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setSpeedingTicket(txtField.getText());
}
});
add(btn);
}
private void setSpeedingTicket(String text) {
try {
int speedTicket = Integer.parseInt(text);
st.setSpeedingTicket(speedTicket);
System.out.println("Speeding ticket set to " +st.getSpeedingTicket());
} catch (NumberFormatException ex) {
System.out.println("Invalid value " +text);
ex.printStackTrace();
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Speeding Ticket");
frame.setSize(400,100);
frame.add(new SpeedingTicketGUI());
frame.setVisible(true);
}
}
You don't need to store values in JText or any GUI componenets...
Use global static variables. For example:
public static int speed_limit;
You can access this variable from ANY method,class, etc.
There are multiple ways to do it.
You can detect textfield changes by using a DocumentListener or if you want (not recommended) by a KeyListener.
The Listener could be implemented directly by your gui class or by your other class. If you want more abstraction you could implement the DocumentListener by your gui class and create a method
public void addSpeedChangeListener(SpeedChangeListener scl) {
this.speedChangeListeners.add(scl);
}
Your SpeedChangeListener could be very simple:
public interface SpeedChangeListener {
public void speedChanged(int value);
}
Then your second class implements the SpeedChangeListener and calls addSpeedChangeListener(this) on your gui class. Inside the gui class, your document listener calls speedChanged(val) for every listener registered.
EDIT
You can also use the Button and call the speedChanged on every listener inside the actionPerformed method of the ActionListener.
I think it would be easier to use a JOptionDialog which pop ups when the button is clicked. That way you can easily get input and also validate the input straight away.
first of all I will introduce what I am trying to do. This is an assignment in university we are making Hotel booking system with JAVA. To go straight to the point, all I need to know is how to update JList when I press button.
listModel = new DefaultListModel<Hotel>();
bookingList = new JList(listModel);
class MouseAdapterMod extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if(e.getSource() == searchButton){
for(lists.getRoomsList() p : lists.getRoomsList())
{
listModel.addElement(p);
}
bookingList.setModel(listModel);
}
In this GUI class I have instance variable (lists) of Hotel class, in Hotel class there are methods
public ArrayList<Rooms> getRoomsList()
{
return roomsList.getListRooms();
}
public ArrayList<Suite> getSuitesList()
{
return roomsList.getListSuites();
}
this returns whole ArrayList of Room class objects and also ArrayList of Suite class.
QUESTION would be is how to show whole ArrayList of Rooms when I press button, in other words how to update JList which consists of objects, by pressing button?
I hope I explained alright.
Your for-each loop is wrong. Try this and see:
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(searchButton)){
ArrayList<Rooms> rooms = lists.getRoomsList();
for(Rooms r : rooms) {
listModel.addElement(r);
}
bookingList.setModel(listModel);
}
}
This still looks sorta messy to me though. A more appropriate approach would be to set an event handler on the searchButton, to populate the JList when searchButton is clicked.
Also, are Rooms and Suites sub classes of Hotel? If not, you'll have to create listModel like this (for rooms):
listModel = new DefaultListModel<Rooms>();
I have these two classes:
ConnectionPanel.class
public class ConnectionPanel extends JPanel implements ActionListener,ItemListener, PropertyChangeListener {
private MasterModel m_masterModel;
private JTextField m_keyField;
public ConnectionPanel(MasterModel masterModel) {
m_masterModel = masterModel;
setLayout(new GridLayout(0, 2));
JPanel panel = null;
panel = new JPanel();
panel.add(new JLabel("Type Key:"));
m_keyField = new JTextField(9);
m_keyField.setText("dertfgdertabcdef");
panel.add(m_keyField);
add(panel);
getChatModel().addPropertyChangeListener(this);
getChatModel().setListen(true);
}
public String getEncryptionKey(){
return m_keyField.getText();
}
}
AudioPlayback.class
public class AudioPlayback extends AudioBase {
// and here I want to be able to get
// somehow String key = ConnectionPanel.getEncryptionKey()
// I tried ConnectionPanel panel = new ConnectionPanel(); but does not work
// it messes my graphical interface
// also there is lots of code here too
}
Do you have any ideas how can I get that field input into my audioplayback.class ?
I totally agree with moffeltje & Luke. This question is simple so that I think you can learn something more basic on Java.
But I review your constructor of ConnectionPanel.Excuse me, do you know constructor?
You can find the details here:
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Now, let's talk about your code. You only give a constructor with one input parameter to ConnectionPanel so that you can't use the constructor without parameters in AudioPlayback.
But the attribute masterModel seems hasn't been called in your ConnectionPanel so that you can roughly use the following code:
// Notice! Don't do this in your production enviroment. It's only for test otherwise you can make sure that you can give the null value to it.
ConnectionPanel panle = new ConnectionPanel(null);
System.out.println(panel.getEncryptionKey());
I'm trying to write a simple retirement calculator for a project.
I'm trying to get a document listener so I can take input from different text fields and use them in my calculations.
For some reason I can't get the DocumentListener to instantiate, and I get an error. I think that I lack understanding of how to do this.
The specific line of code that is giving me an error is this:
DocumentListener DL = new DocumentListener();
Here is the class where I try to use this:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class TextFields extends JPanel implements DocumentListener
{
public TextFields()
{
setLayout(new GridLayout(5,1));
setFont(new Font("Tahoma", Font.PLAIN, 14));
DocumentListener DL = new DocumentListener();
JTextField age = new JTextField("Age");
age.getDocument().addDocumentListener(DL);
JLabel ageLabel = new JLabel("Age: ");
JTextField initialSavings = new JTextField("Intial Savings");
JLabel ISLabel = new JLabel("Inital Savings: ");
JTextField ageRetire = new JTextField("Retirement Age");
JLabel RALabel = new JLabel("Retirement Age: ");
JTextField inflation = new JTextField("Inflation Rate");
JLabel inflationLabel = new JLabel("Inflation Rate: ");
JTextField dailySavings = new JTextField("Daily Savings");
JLabel DSLabel = new JLabel("Daily Savings: ");
JTextField DeathAge = new JTextField("Age Of Death");
JLabel DALabel = new JLabel("When will you die? ");
JTextField retirementIncome = new JTextField("Retirement Income:");
JLabel RILabel = new JLabel("Retirement Income: ");
JTextField interest = new JTextField("Interest Rate");
JLabel interestLabel = new JLabel("Interest: ");
add(ageLabel);
add(age);
add(ISLabel);
add(initialSavings);
add(RALabel);
add(ageRetire);
add(inflationLabel);
add(inflation);
add(DSLabel);
add(dailySavings);
add(DALabel);
add(DeathAge);
add(interestLabel);
add(interest);
add(RILabel);
add(retirementIncome);
}
#Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
#Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
#Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
}
Since I am beginning programer, I would appreciate simple answers that won't require a huge amount knowledge to understand.
Thank you very much for your time and help!
Roy.
Short version:
...
// DocumentListener DL = new DocumentListener();
JTextField age = new JTextField("Age");
age.getDocument().addDocumentListener(this);
...
Long version:
First, I'm going to give you the error explanation. After that, I'm including a particular case suitable for your needs.
That error means that your DocumentListener is either an abstract class, or an interface (read about these two, then you'll get the idea).
The solution is either to look for subclasses of it (press CTRL + T while the class name is selected in the Eclipse IDE editor) OR to create an anonymous class right where you're instantiating it (see example below). Keep in mind that instantiating interfaces is generally not a good idea (not unless you know what you're doing), i.e. interfaces should be implemented by separate classes, and then instantiate THOSE classes.
DocumentListener dl = new DocumentListener()
{
// implement abstract methods here
};
Knowing this, we now have to particularise all of this to your code.
When attaching listeners to different elements (usually, listeners are interfaces), the code standard is to add the listener as an anonymous class directly as the API parameter, like so:
age.getDocument().addDocumentListener(new DocumentListener()
{
// implement necessary methods here
});
A quick Google Search instantly tells me what methods you need to implement there. Finally, your code should look like:
age.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
}
public void insertUpdate(DocumentEvent e)
{
}
public void removeUpdate(DocumentEvent e)
{
}
});
Inside these methods, you may do whatever you want with those receiving events (of type DocumentEvent - read the javadoc)
ANOTHER way to do it (the way that you've already started doing), is to implement the DocumentListener directly in your working class, and then implement those methods there (as you did - notice the three overridden methods at the end of your class). In this case, all you have to do is tell the age.getDocument() where it can find the listener.
age.getDocument().addDocumentListener(this);
By writing this as listener, it means that when DocumentEvents are thrown, the execution will pass through those methods of yours there (changedUpdate, insertUpdate, removeUpdate).
As you can see in your TextFields class declaration you are implementing DocumentLstener which means that's an interface and you can't instantiate an interface.
replace the problematic line with this
DocumentListener DL = new TextFields();
Since TextFields has implemented the DocumentListener interface everything will be fine.
Or you can use a separate or inner class for listener.