0

I have a JLabel inside of a JPanel and when I input some message into the showOptionDialog and select the "OK" button, the JLabel should print out the message I entered. However, the codes I have doesn't even go into the paintComponent() method in my TextLabel class (I used a simple trace statement to check this). I have also tried adding a new MouseListener to my tagPanel but it still doesn't work.

My program code is too lengthy so I have only show the codes that are relevant.

Main Class:

//...list of global variables

public void go()
{       
    //...other codes

    image = new DrawLabel();
    imgPanel.add(image);
    imgPanel.setBorder(new LineBorder(Color.BLACK));
    image.addMouseListener(new MouseHandler());

    text = new TextLabel();
    tagPanel.add(text);
    tagPanel.setBorder(new LineBorder(Color.BLACK));
    tagPanel.setPreferredSize(new Dimension(200, 480));

    frame.add(imgPanel, BorderLayout.WEST);
    frame.add(tagPanel, BorderLayout.EAST);
    frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

showOptionDialog in MouseHandler Class:

String[] options = {"OK"};
JPanel popOut = new JPanel();
JLabel lbl = new JLabel("Enter keywords: ");
JTextField txt = new JTextField(50);
popOut.add(lbl);
popOut.add(txt);
int selectedOption = JOptionPane.showOptionDialog(null, popOut, "Tag", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);

if(selectedOption == 0)
{
    String entered = txt.getText();
    String[] parts = entered.split(", ");

    for(int i=0; i<parts.length; i++)
    {
        keywords.add(parts[i]);
    }

}
else
{
    System.out.println("untitled");
}

TextLabel Class:

private class TextLabel extends JLabel
{
    public void paintComponent(Graphics g)
    {
        if(keywords != null)
        {
            super.paintComponent(g);

            String words = "";

            for(int i=0; i<keywords.size(); i++)
            {
                words = words + keywords.get(i) + ", "; 
            }

            int fontSize = 20;
            g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
            g.setColor(Color.BLACK);

            g.drawString(words, 50, 50);
            repaint();

            System.out.println("here");
        }
        else
        {
            super.paintComponent(g);
            repaint();
        }
    }
}
jl90
  • 639
  • 2
  • 10
  • 24

0 Answers0