I do not understand how repaint(); works.
I tried to look for a tutorial, but never found anything and the naswers on 'similar questions' also didn't really help.
Here is the most basic code that I could write that should work, but doesn't:
static String done = "0";
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setResizable(false);
JPanel panel = new JPanel();
frame.setSize(800, 500);
frame.setLocation(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton end = new JButton(done);
end.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
done += Integer.valueOf(1);
panel.repaint();
}
});
panel.add(ende);
frame.add(panel);
frame.setVisible(true);
}
Obviously this is just a button that should be repainted once clicked with a number+1.
Followup question: How do I tell a panel to repaint itself while inside another panel? Here is the base code that should work:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class Repaint
{
static String done = "0";
public static void main(String[] args)
{
new Repaint();
}
public Repaint()
{
createframe();
}
public void createframe()
{
JFrame frame = new JFrame();
frame.setResizable(false);
JPanel panel = new JPanel();
frame.setSize(800, 500);
frame.setLocation(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border bo = new LineBorder(Color.black);
JMenuBar bar = new JMenuBar();
bar.setBorder(bo);
JMenu menu = new JMenu("Edit");
JMenuItem stats = new JMenuItem("Edit the button");
stats.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
createbox();
}
});
menu.add(stats);
JLabel end = new JLabel(done);
bar.add(menu);
frame.setJMenuBar(bar);
panel.add(end);
frame.add(panel);
frame.setVisible(true);
}
public void createbox()
{
JFrame framebox = new JFrame();
framebox.setResizable(false);
JPanel panelbox = new JPanel();
framebox.setSize(800, 500);
framebox.setLocation(500, 400);
JButton end = new JButton(done);
end.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
done += String.valueOf(1);
framebox.dispose();
}
});
panelbox.add(end);
framebox.add(panelbox);
framebox.setVisible(true);
}
}
Basicially pressing the button in frame 2 increases the number of the String "done" by one. But it does not repaint it in the original frame.