我在JLabel
内有一个JPanel
,当我在showOptionDialog
输入一些消息并选择" OK"按钮,JLabel
应该打印出我输入的消息。但是,我所拥有的代码甚至没有进入paintComponent()
类中的TextLabel
方法(我使用了一个简单的跟踪语句来检查这一点)。我还尝试向MouseListener
添加新的tagPanel
,但它仍然无效。
我的程序代码太冗长,所以我只显示相关的代码。
主要类别:
//...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);
}
MouseHandler类中的showOptionDialog:
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类:
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();
}
}
}