ı have problem about delete a empty string values like we can see in picture,
in the first time if here is empty he give a error but after that even we write some strings in that blank,its still giving the same error how can ı delete this label before the sending again How can ı fix that problem ı tried some codes but nothing worked well please help about that
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class ui {
public static void main(String[] args) {
uiVision();
}
public static void uiVision() {
ImageIcon eyes = new ImageIcon("a.png");
Globals.jf.setTitle("Deneme Uygulamasi");
Globals.jf.setLocation(100,200);
JLabel label1,label2,label3;
Globals.jf.getContentPane().setLayout(new FlowLayout());
JTextField isim = new JTextField(20);
JTextField soyisim = new JTextField(20);
JTextField pasaport = new JTextField(20);
JTextField mail = new JTextField(20);
JPasswordField passwordField = new JPasswordField(10);
JPasswordField passwordField2 = new JPasswordField(10);
JButton buton1 = new JButton("Send");
JButton buton2 = new JButton(eyes);
JButton buton3 = new JButton(eyes);
JButton buton4 = new JButton("!");
label1 = new JLabel("Name:");// -8
label2 = new JLabel("Surname:");// -9
label3 = new JLabel("Passaport-ID:");//+ 10
JLabel label4 = new JLabel("Mail:");// +10
JLabel label5 = new JLabel("Password:");//+10
JLabel label6 = new JLabel("Re-Password:");// +20
buton1.setBounds(170,400,150,30);
buton2.setBounds(320,190,50,30);
buton3.setBounds(320,230,50,30);
buton4.setBounds(370,230,50,30);
isim.setBounds(170,30,150,30);
soyisim.setBounds(170,70,150,30);
pasaport.setBounds(170,110,150,30);
mail.setBounds(170,150,150,30);
passwordField.setBounds(170,190,150,30);
passwordField2.setBounds(170,230,150,30);
label1.setBounds(125,30,150,30);
label2.setBounds(106,70,150,30);
label3.setBounds(90,110,150,30);
label4.setBounds(132,150,150,30);
label5.setBounds(105,190,150,30);
label6.setBounds(91,230,150,30);
Globals.jf.add(buton1);Globals.jf.add(buton2);Globals.jf.add(buton3);
Globals.jf.add(label1);Globals.jf.add(label2);Globals.jf.add(label3);Globals.jf.add(label4); Globals.jf.add(label5);Globals.jf.add(label6);
Globals.jf.add(isim);Globals.jf.add(soyisim);Globals.jf.add(pasaport);Globals.jf.add(mail);Globals.jf.add(passwordField);Globals.jf.add(passwordField2);
Globals.jf.setSize(1000,500);
buton2.addActionListener(l -> {
if ( passwordField.getEchoChar() != '\u0000' ) {
passwordField.setEchoChar('\u0000');
} else {
passwordField.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}
});
buton3.addActionListener(l -> {
if ( passwordField2.getEchoChar() != '\u0000' ) {
passwordField2.setEchoChar('\u0000');
} else {
passwordField2.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}
});
buton1.addActionListener(e -> {
checkEmpty(isim.getText(),label1.getText(),label1);
checkEmpty(soyisim.getText(),label2.getText(),label2);
checkEmpty(pasaport.getText(),label3.getText(),label3);
checkEmpty(mail.getText(),label4.getText(),label4);
ExitWhenLoopEnd();
Globals.globalInt = 0;
System.out.println(passwordField.getPassword());
System.out.println(passwordField2.getPassword());
Globals.clickCount++;
});
Globals.jf.setLayout(null);
Globals.jf.setVisible(true);
Globals.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void checkEmpty(String value,String label,JLabel labelname) {
Integer syc = Integer.valueOf(0);
if(value != null && !value.trim().isEmpty()) {
if(Globals.globalInt != 4) {
Globals.globalInt++;
}
syc = 1;
}
else {
CreateEmptyMessageError(label,labelname,Globals.jf);
syc = -1;
}
System.out.println(syc);
}
public static void CreateEmptyMessageError(String labelError,JLabel label,JFrame jf) {
Globals.labelx = new JLabel(labelError.split(":")[0]+" is empty!");
Globals.labelx.setBounds(label.getBounds().x+250,label.getBounds().y,label.getWidth(),label.getHeight());
Globals.labelx.setForeground(Color.RED);
jf.add(Globals.labelx);
jf.revalidate();
jf.repaint();
}
public class Globals {
public static int globalInt = 0;
public static JLabel labelx = null;
public static JFrame jf = new JFrame();
public static int clickCount = 0;
public static int lastVal = 0;
public static int syc = 0;
}
public static void ExitWhenLoopEnd() {
if(Globals.globalInt == 4) {
System.exit(0);
}
}
}
Your problem is that you're creating a new JLabel and adding it to the GUI each time CreateEmptyMessageError(...) is called, and by doing this, you have no reference to this object, and no way to change its state.
The solution is to not do this, to instead create the error message label when you create the GUI itself, assign it to an instance field, and in that method above to not create a new JLabel object but rather to set the text of the existing object, one that shows a warning if the JTextField is empty, and one that sets the JLabel text to the empty String, "", if the JTextField has text.
Also,
As Progman has suggested in comments, avoid the use of static fields and methods unless the use suggests that these should be used, and this isn't the case here. Instead, use private instance fields and methods. This will make your code easier to mock/test/extend and re-use, this reduces potential for hard to identify bugs by reducing your code's cyclomatic complexity and coupling.
Avoid the use of null layouts and setBounds(...) and instead learn and use the layout managers.
Learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Give your fields names that describe what they represent, making your code self-commenting and easier to understand.
Related
I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base
I have a linked list that store bunch of instrument as an object. And i want to access and display it on a GUI. What are some good ways to access it instead of just create a method and return the list to the GUI.
Pls gives some advice.
I will be appreciated.
It depends if you mean the class or an instance of your class. If you mean a class its just an import. If you need an instance of a class there are other ways like making it static (quick and dirty) or using a singleton if just one copy is allowed.
class InstrumentDisplayPanel extends JPanel implements ActionListener {
JPanel status = new JPanel();
JPanel action = new JPanel();
JLabel name = new JLabel();
JLabel number = new JLabel();
JButton next = new JButton("next");
JButton previous = new JButton("previous");
InstrumentDisplayPanel() {
this.setPreferredSize(new Dimension(200,200));
DoublyLinkedList<Instrument> instrumentList = FileRead.loadInstrument();
Node tempNode = instrumentList.getFirstItem();
Item tempItem = (Item)tempNode.getItem();
name.setText(tempItem.getName());
number.setText(tempItem.getNumber());
status.add(name);
status.add(number);
action.add(next);
action.add(previous);
add(status);
add(action);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == next) {
}
}
}
public static DoublyLinkedList<MusicSheet> loadMusicSheet(){
System.out.println("I am loading");
Scanner musicSheetInput = null;
try
{
musicSheetInput = new Scanner(new File("musicSheet.txt"));
}
catch(FileNotFoundException instrument)
{
System.out.println("File does Not Exist Please Try Again: ");
}
DoublyLinkedList<MusicSheet> musicSheetList = new DoublyLinkedList<MusicSheet>();
while (musicSheetInput.hasNextLine()){
String name = musicSheetInput.next();
String number = musicSheetInput.next();
String description = musicSheetInput.nextLine();
if(name.equals("GuitarSheet")){
musicSheetList.add(new GuitarSheet(name,number,description));
}
else if(name.equals("ViolinSheet")){
musicSheetList.add(new ViolinSheet(name,number,description));
}
else if(name.equals("CelloSheet")){
musicSheetList.add(new CelloSheet(name,number, description));
}
}
musicSheetList.display();
return musicSheetList;
}
I am making a Library for my pupils to create a GUI easy in Java,
but if they press a button in the Interface it should run a method created by them.
Is there any way to do this?
I am not really into Java, but the curriculum wants me to:(
You can use reflection to run their class without requiring they implement an interface although you would still have to provide instructions to limit the argument types. This works only for methods with no arguments.
java.awt.EventQueue.invokeLater(() -> {
JFrame frm = new JFrame();
JPanel pnl = new JPanel();
frm.add(pnl);
pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));
pnl.add(new JLabel("Class"));
JTextField classField = new JTextField();
pnl.add(classField);
pnl.add(new JLabel("Method"));
JTextField methodField = new JTextField();
pnl.add(methodField);
JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(300, 300));
JButton btn = new JButton("Run");
pnl.add(btn);
pnl.add(area);
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
area.append(new String(new byte[]{(byte) b}));
}
}));
btn.addActionListener(e -> {
try {
Class cls = Class.forName(classField.getText());
Method m = null;
Method ma[] = cls.getDeclaredMethods();
String methodName = methodField.getText().trim();
m = cls.getMethod(methodName,new Class[]{});
Object o = cls.newInstance();
Object mr = m.invoke(o);
if(null != mr) {
area.append("\nreturned "+mr.toString()+"\n");
}
} catch (Exception ex) {
ex.printStackTrace();
area.append("\nException "+ex.getMessage()+"\n");
}
});
frm.pack();
frm.setVisible(true);
});
given a class like:
public class StudentClass {
public void print10() {
int sum= 0;
for(int i = 0; i< 10; i++ ) {
System.out.println("i = "+i);
sum+=i;
}
}
}
The fields would be need to be filled with StudentClass and print10 and the compiled class needs to be on your classpath.
Perhaps a better option would be to teach Processing (https://processing.org/). This is essentially java since the Processing code gets pasted into a java class behind the scenes but is much more oriented to get beginners drawing graphical sketches. I guess you'd have to ask your administration if they would go for it and at some point the students would need to be able to write the code the processing tools are generating for them.
How to validate a textfield to enter only 4 digits after the decimal point in Swing?
Any validation in Swing can be performed using an InputVerifier.
1. First create your own input verifier:
public class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
BigDecimal value = new BigDecimal(text);
return (value.scale() <= Math.abs(4));
} catch (NumberFormatException e) {
return false;
}
}
}
2. Then assign an instance of that class to your text field. (In fact any JComponent can be verified)
myTextField.setInputVerifier(new MyInputVerifier());
Of course you can also use an anonymous inner class, but if the validator is to be used on other components, too, a normal class is better.
Also have a look at the SDK documentation: JComponent#setInputVerifier.
You could probably accomplish the same with DocumentListener. All you have to do is validate the input string against the desired string pattern. In this case, the pattern seems to be one or more digits, followed by a period, AND exactly 4 digits after the decimal point. The code below demonstrates using DocumentListener to accomplish this:
public class Dummy
{
private static JTextField field = new JTextField(10);
private static JLabel errorMsg = new JLabel("Invalid input");
private static String pattern = "\\d+\\.\\d{4}";
private static JFrame frame = new JFrame();
private static JPanel panel = new JPanel();
public static void main(String[] args)
{
errorMsg.setForeground(Color.RED);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 0, 0, 5);
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.SOUTH;
panel.add(errorMsg, c);
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
panel.add(field, c);
frame.getContentPane().add(panel);
field.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void removeUpdate(DocumentEvent e)
{
validateInput();
}
#Override
public void insertUpdate(DocumentEvent e)
{
validateInput();
}
#Override
public void changedUpdate(DocumentEvent e) {} // Not needed for plain-text fields
});
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void validateInput()
{
String text = field.getText();
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (m.matches())
{
errorMsg.setForeground(frame.getBackground());
}
else
{
errorMsg.setForeground(Color.RED);
}
}
}
As long as the text field does not contain a valid input, the error message is shown like the image below.
Once the input is validated, the error message will not be visible.
Of course, you can replace the validation action to whatever you need. For example, you may want to display some popup when a button is clicked if the input is not valid, etc.
I threw this together to show an alternative to answer given already. There might be cases when this solution might be more suitable. There might be cases when the given answer might be more suitable. But one thing is certain, alternatives are always a good thing.
I am a beginner with java and has got a problem that I just cant solve.
I am trying to add strings to my array, I have tested my array so that work. But my problem is that I have created an actionlistener and trying to get the text from another class and then add it to the array.
My Buttonlistener:
public class ButtonListener extends AddToLibrary implements ActionListener {
public void actionPerformed(ActionEvent e) {
Database dt = new Database();
dt.add(textType, textTitle, textSort, textDesc);
} }
I got a friend who told me that I am creating a new database every time I pushes the button, but how do I do if I just want to "load" it? Can clear that database is the classname for my array.
The more "funny" part of this is that when I run it in eclipse it goes to debugger without showing me anything clear that is wrong, and because of my limited knowledge in java this is too much to me.
My buttonlistener is geting the information from AddToLibrary and it looks like this:
public class AddToLibrary extends JPanel{
public String textTitle;
public String textSort;
public String textDesc;
public String textType;
public AddToLibrary() {
// Förklarande text
JLabel titel = new JLabel("Titel");
JLabel sort = new JLabel("Genre");
JLabel desc = new JLabel("Beskriving");
// Textrutor
JTextField textTitel = new JTextField(null, 20);
textTitel.setToolTipText("ex. Flickan som lekte med elden");
JTextField textSort = new JTextField(null, 10);
textSort.setToolTipText("ex. Skräck, Action");
JTextField textDesc = new JTextField(null, 15);
textDesc.setToolTipText("ex. Stieg Larsson");
// Knappar
JButton addButton = new JButton("Lägg till");
addButton.addActionListener(new ButtonListener()); //Lyssna på knapp
// Combobox
JComboBox comboBox = new JComboBox();
comboBox.addItem("Film");
comboBox.addItem("CD");
comboBox.addItem("Bok");
comboBox.addItem("Annat");
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
public String getTitelText(JTextField titelText) {
textTitle = "" + titelText.getText();
return textTitle;
}
public String getDescText(JTextField descText) {
textDesc = "" + descText.getText();
return textDesc;
}
public String getSortText(JTextField sortText) {
textSort = "" + sortText.getText();
return textSort;
}
public String getTypeText(JComboBox comboBox) {
return textType = "" + (String) comboBox.getSelectedItem() + ".png";
}
}
But it do not work and I cant understand why it isnt working, so if anyone has some time over to help me I would be pleased.
Thanks!
One fault is here:
public class ButtonListener extends AddToLibrary implements ActionListener {
extending AddToLibrary creates a weird inheritance problem.
The simple solution is to define the ButtonListener inline:
final Database dt = new Database();
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dt.add(getTypeText(comboBox), getTitelText(textTitel), getSortText(textSort), getDescText(textDesc));
}
}); // Lyssna på knapp
One important change is to create one instance of Database to which the strings are added (as Amit Kumar already pointed out).
There were a lot of problems with your code, mostly illegal constructions. My advice is to get a good Java tutorial/book and take notice of how they solve the problems. Also if you use Eclipse (or another modern IDE) it will notify you of any illegal constructions and will try to propose solutions.
One last note, the public Strings and the JTextFields have the same name, this creates a problem for the computer as it does not know which one you are referring to (this is called shadowing). Define unique names for each variable within a class so you do not confuse the compiler or yourself.
=====================================
I have done a little work on your code and I arrived at the following. (It may be improved even further, but this is at least a lot better in terms of legality and readability)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddToLibrary extends JPanel {
private static final long serialVersionUID = 1L;
private Database database = new Database();
private JComboBox comboBox = new JComboBox(new String[]{"Film", "CD", "Bok", "Annat"});
private JButton addButton = new JButton("Lägg till");
private JTextField textTitel = new JTextField(null, 20);
private JTextField textSort = new JTextField(null, 10);
private JTextField textDesc = new JTextField(null, 15);
private JLabel titel = new JLabel("Titel");
private JLabel sort = new JLabel("Genre");
private JLabel desc = new JLabel("Beskriving");
public AddToLibrary() {
textTitel.setToolTipText("ex. Flickan som lekte med elden");
textSort.setToolTipText("ex. Skräck, Action");
textDesc.setToolTipText("ex. Stieg Larsson");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database.add(comboBox.getSelectedItem() + ".png",
textTitel.getText(),
textSort.getText(),
textDesc.getText()
)
}
}); // Lyssna på knapp
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
}
public class ButtonListener extends AddToLibrary implements ActionListener {
private Database dt = new Database();
public void actionPerformed(ActionEvent e) {
dt.add(textType, textTitle, textSort, textDesc);
}
}
should work. Or better, the database should be created in AddToLibrary and passed to ButtonListener in its constructor. Sorry I do not have the time to check the code for you, but if this does not work, you can notify.