.drawLine on event (button click) Jpanel/Jbutton/JTabbedPane
I know how to do action listeners for button clicks in/on swing, but I have this class which does some stuff but I want it a function/event that when a button is clicked it runs a metho开发者_开发技巧d similiar to the PaintComponent below... (draws a line)
class CustomPanel extends JPanel {
private int destx = 100;
private int desty = 100;
private int startx = 0;
private int starty = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(startx, starty, destx, desty);
}
}
How would I call this paintcomponent (Or a similar one which draws a line) from a action listener?
Here is my actionlistener: (Its on GUI.java while the code above is on CustomPanel.java)
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//Does other stuff but removed for simplifying
CustomPanel cp = new CustomPanel();
}
}
Thanks alot,
Your question didn't make sense to me in your last posting and it still doesn't make sense to me in this posting.
You still haven't posted a SSCCE that attempts to demonstrate what you want to do.
If you have a "login panel", typically that is done by creating a modal JDialog.
If you are trying to draw a diagonal across the top of all components in the frame, then you would need to use a Glass Pane or a Layered Pane.
Read the section from the Swing tutorial on How to Use Root Panes for examples and more detailed information.
You need to add it to gui. Something like this:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
parentPanel.add(new CustomPanel());
parentPanel.revalidate();
parentPanel.repaint();
}
});
But if you only want to draw a line on the current container that's another thing...
Simply adding your CustomPanel
to any other JComponent
and updating the UI should do the trick. Swing takes care of all the painting for you.
Here is a reslly useful guide to swing painting;
http://java.sun.com/products/jfc/tsc/articles/painting/#paint_process
精彩评论