how can i make save button work by writing this code? - java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class DiceFrame extends JFrame{
ImageIcon[] dice_im = new ImageIcon[7];
String score="start";
JPanel mainPanel= new JPanel();
JPanel scorePanel=new JPanel();
JPanel buttonPanel =new JPanel();
JLabel picLabel = new JLabel();
JTextArea scorefield = new JTextArea();
JButton roll= new JButton("roll the dice");
JButton save = new JButton("save");
ActionListener action;
ActionListener output;
public DiceFrame(){
super();
setSize(600, 600);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(save);
buttonPanel.add(roll);
mainPanel.add(picLabel);
picLabel.setIcon(dice_im[0]);
scorePanel.add(scorefield);
scorefield.setText(score);
action = new DiceActionListener();
roll.addActionListener(action);
}
private void loadImage(){
dice_im [0]= new ImageIcon("1.jpg");
dice_im[1] = new ImageIcon("2.jpg");
dice_im[2] = new ImageIcon("3.JPG");
dice_im[3] = new ImageIcon("4.JPG");
dice_im[4] = new ImageIcon("5.JPG");
dice_im[5] = new ImageIcon("6.JPG");
}
public static void main(String args[]){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class DiceActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random rg = new Random();
int k = rg.nextInt(6) + 1;
picLabel.setIcon(dice_im[k]);
}
}
class SaveActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { //NEW code
String out_file_name = "dice_score.txt";
try {
File outputfile = new File(out_file_name);
PrintStream out = new PrintStream(
new FileOutputStream(outputfile));
out.println(score);
out.flush();`
out.close();
} catch (IOException y) {
System.out.println("IO problem.");
}
}
}
}
How can i make save button work by writing this code?
Whenever i run it roll button works but the save button doesn't work?
this is a program for the rolling the dice but i need to make the save button work, Can anyone please help with that?
how can i link dice_score.txt file to this program?

Action listener is not added to Save Button.
save.addActionListener(new SaveActionListener());

Add this at the end of DiceFrame():
save.addActionListener(new SaveActionListener());

See
action = new DiceActionListener();
roll.addActionListener(action);
well you have to follow this pattern and do
SaveActionListener action2 = new SaveActionListener ();
save.addActionListener(action2);
Although in reality it is not necessary to create a named instance and you can simply do
save.addActionListener (new SaveActionListener ());

Related

Java Swing Eclipse Program seems to compile; Wont run however

ive recently just got back into programming Swing and java in general and am quite rusty. My program im trying to finish is seeming to compile going by eclipse, but it wont run, its telling me it doesn't have a main type. And its not giving me an error notifications so im kind of stuck here at the moment.
I've never seen this error before so not sure what it is, or cant remember what it is if I have. Any ideas what im doing wrong or should fix to get this to run, thanks:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
import javax.swing.Timer.*;
import javax.swing.event.*;
public class FamousLocations extends JFrame implements ChangeListener, ActionListener, Runnable
{
private static final long serialVersionUID = 0;
JMenuBar p = new JMenuBar();
int Selected = 0;
ImageIcon a = new ImageIcon("america.jpg");
ImageIcon j = new ImageIcon("Japan.jpg");
ImageIcon c = new ImageIcon("china.jpg");
ImageIcon i = new ImageIcon("ireland.jpg");
ImageIcon t = new ImageIcon("thailand.jpg");
ImageIcon ca = new ImageIcon("Niagra-Falls.jpg");
Icon[] pics = {a,j,c,i,t,ca};
private JLabel ImageLabel = new JLabel(pics[Selected]);
String america = ("Grand Canyon, America");
String japan = ("Kinkaku-ji (The Golden Pavilion) Kyoto, Japan");
String china = ("Mount Huangshan, China");
String ireland = ("Newgrange, Ireland");
String thailand = ("Bangkok ,Thailand");
String canada = ("Niagra Falls , Canada");
String[] Box = {america, japan, china, ireland, thailand, canada};
JTextArea lo = new JTextArea(Box[Selected]);
String InfoGrand = new String ("desciption");
String InfoHiro = new String ("desciption");
String InfoMount = new String ("desciption");
String InfoNew = new String ("desciption");
String InfoBang = new String ("desciption");
String InfoNiag = new String ("desciption");
String[] Info = {InfoGrand, InfoHiro, InfoMount, InfoNew, InfoBang, InfoNiag};
JTextArea ta = new JTextArea(Info[Selected]);
private JTabbedPane tp = new JTabbedPane();
public JSlider slider = new JSlider();
private JPanel dropd = new JPanel();
private JPanel checkb = new JPanel();
private JPanel ImagePan = new JPanel();
private JPanel InfoPan = new JPanel();
private JCheckBox slider1 = new JCheckBox ("Show Slider" , true);
private JCheckBox slideshow1 = new JCheckBox ("Slideshow", false);
JComboBox com1 = new JComboBox(Box);
public FamousLocations(){
setTitle("My Bucket List");
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
getContentPane().setSize(1000,1000);
getContentPane().add(dropd);
getContentPane().add(slider,BorderLayout.SOUTH);
getContentPane().add(slider1);
getContentPane().add(slideshow1);
getContentPane().add(tp);
slider.setValue(0);
slider.addChangeListener(this);
slider.setOrientation(JSlider.HORIZONTAL);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setMaximum(5);
slider.setSnapToTicks(true);
ImagePan.add(ImageLabel);
checkb.add(com1);
checkb.add(slider1);
checkb.add(slideshow1);
tp.addTab("Photo", ImagePan);
tp.addTab("Description of Area", InfoPan);
tp.addTab("Index and Options", checkb);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
slider1.setVisible(true);
slider1.addActionListener(this);
slideshow1.setVisible(true);
slideshow1.addActionListener(this);
com1.addActionListener(this);
com1.addActionListener(this);
JMenu help = new JMenu("HELP");
JMenuItem AL1 = help.add("how to use");
JMenuItem AL2 = help.add("EXIT");
p.add(help);
this.setJMenuBar(p);
AL1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"error");
}
});
AL2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
setSize(250,250);
setVisible(true);
}
public void change(){
JTextArea ta=new JTextArea(Box[Selected]);
ImagePan.removeAll();
ImagePan.add(ImageLabel=new JLabel(pics[Selected]));
InfoPan.removeAll();
InfoPan.add(ImageLabel=new JLabel(Info[Selected]));
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
ImagePan.repaint();
validateTree();
}
public void run(){
for(int y = 0;y==y+1; y++){
slider.setValue(y);
try{
Thread.sleep (1000);
}
catch (Exception e) {}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==slider1) {slider.setVisible(slider1.isSelected());}
else if(e.getSource()==com1)
{Selected=com1.getSelectedIndex(); change();}
else if(e.getSource()==slideshow1)
{new Thread(this).start(); }
}
public void stateChanged(ChangeEvent e) {
if(e.getSource()==slider){Selected=slider.getValue();change();}
}
}

error: illegal start of expression 1 error

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.lang.*;
import java.util.*;
public class Life {
public static void main (String[] args){
JFrame frame = new JFrame("Interest Calculator");
frame.setVisible(true);
frame.setSize(300,100);
frame.setBackground(Color.magenta);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Simple Interest");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("Compound Interest");
panel.add(button2);
button2.addActionListener (new Action2());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Simple");
frame2.setVisible(true);
frame2.setSize(300,100);
JPanel panel = new JPanel();
frame2.add(panel);
JButton button = new JButton("Ordinary");
panel.add(button);
button.addActionListener (new Ordinary());
JButton button2 = new JButton("Exact");
panel.add(button2);
button2.addActionListener (new Exact());
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame3 = new JFrame("Compound Interest");
frame3.setVisible(true);
frame3.setSize(300,100);
JPanel panel = new JPanel();
frame3.add(panel);
JButton button = new JButton("Compounded");
panel.add(button);
JButton button2 = new JButton("Continously");
panel.add(button2);
}
}
static class Ordinary implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame4 = new JFrame("Simple");
frame4.setVisible(true);
frame4.setSize(300,100);
JPanel panel = new JPanel();
frame4.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
button.addActionListener (new Approximate());
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Exact implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame5 = new JFrame("Exact");
frame5.setVisible(true);
frame5.setSize(300,100);
JPanel panel = new JPanel();
frame5.add(panel);
JButton button = new JButton("Approximate");
panel.add(button);
JButton button2 = new JButton("Actual");
panel.add(button2);
}
}
static class Approximate implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame6 = new JFrame("Simple");
frame6.setVisible(true);
frame6.setSize(300,100);
JPanel panel = new JPanel();
frame6.add(panel);
frame6.setVisible(true);
frame6.setSize(300,300);
frame6.setLayout(null);
frame6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField P = new JTextField();
panel.add(P);
P.setText("Enter Principal");
JTextField r = new JTextField();
panel.add(r);
r.setText("Enter Rate");
JTextField t = new JTextField();
panel.add(t);
t.setText("Enter Year");
JButton button = new JButton("Calculate");
panel.add(button);
button.addActionListener (new button());
static class button implements ActionListener {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
P = Float.parseFloat(P.getText());
r = Float.parseFloat(r.getText());
t = Float.parseFloat(t.getText());
result = P*r/100*t/360;
button.setText(String.valueof(result));
}
}
}
}
}
So this is my code to create a compound calculator but I have a problem it is the illegal start of expression.please help me for my project.
Below is partially fixed part of the code which causes problems. Next time include full error code, and try to show only relevant part of the code.
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent e) {
float P,r,t,result ;
//P = Float.parseFloat(P.getText()); // P makes no sens here - its float !!! and uninitialized
//r = Float.parseFloat(r.getText()); // same for r
//t = Float.parseFloat(t.getText()); // same for t
result = P*r/100*t/360;
button.setText(String.valueOf(result));
}
};
button.addActionListener (listener);

Auto typer doesn't stop when "Stop Spam" button is pushed

I've created an auto typer because I've always wanted to know how they work. Only problem is when I click the stop button, it doesn't stop and it freezes my system.
I've tried changing the interval time, and it still doesn't stop when the stop button is pushed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class AutoSpammer{
private static int interval;
private static Timer timerMain;
private static JTextField txtSpam;
private static JTextField txtInterval;
private static JButton btnStart;
private static JButton btnStop;
public static void main(String[]args){
ActionListener taskSpam = new ActionListener(){
public void actionPerformed(ActionEvent evt) {
sendkeys(txtSpam.getText());
}
};
ActionListener taskStartTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.setDelay(Integer.parseInt(txtInterval.getText()));
timerMain.start();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
txtInterval.setEnabled(false);
}
};
ActionListener taskStopTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.stop();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
txtInterval.setEnabled(true);
}
};
btnStart = new JButton("Start Spam");
btnStop = new JButton("Stop Spam");
JLabel lbl1 = new JLabel("Enter Text:");
JLabel lbl2 = new JLabel("Interval:");
timerMain = new Timer(1,taskSpam);
txtSpam = new JTextField("Enter text:", 13);
txtInterval = new JTextField("3000",3);
btnStart.addActionListener(taskStartTimer);
btnStop.addActionListener(taskStopTimer);
btnStop.setEnabled(false);
JPanel intervalpane = new JPanel();
intervalpane.add(lbl2,BorderLayout.EAST);
intervalpane.add(txtInterval,BorderLayout.WEST);
JPanel bottompane = new JPanel();
bottompane.add(btnStart,BorderLayout.EAST);
bottompane.add(btnStop,BorderLayout.CENTER);
bottompane.add(intervalpane,BorderLayout.WEST);
JPanel toppane = new JPanel();
toppane.add(lbl1,BorderLayout.EAST);
toppane.add(txtSpam,BorderLayout.NORTH);
JPanel pane = new JPanel(new BorderLayout());
pane.add(toppane,BorderLayout.NORTH);
pane.add(bottompane,BorderLayout.SOUTH);
JFrame frame = new JFrame("Spammer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
private static void sendkeys(String text) {
try {
Robot robot = new Robot();
text = text.toUpperCase();
for(int i = 0; i < text.length(); i++)
robot.keyPress(text.charAt(i));
robot.keyPress(KeyEvent.VK_ENTER);
}catch(java.awt.AWTException exc) {
System.out.println("error");
}
}
}
program works fine for me. Stop does stop the robot. I added a simple System.out what has been pressed and this stops

Java Simple Simulator

I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Firstly capitalize the name of your class always in Java, then check this code :
public class Sim extends JPanel {
public Sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/1.png");
Icon c = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/2.png");
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
final JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
button.addActionListener(new HandlerClass(label));
}
private class HandlerClass implements ActionListener{
final JLabel label;
public HandlerClass(JLabel label){
this.label = label;
}
public void actionPerformed(ActionEvent e)
{
label.setText("SSSSSSSSSSSSSsssss");
JOptionPane.showMessageDialog(null, "Something");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new Sim());
frame.setVisible(true);
}
}

How do I hide the current JPanel and show a new one with a button in Java?

I unfortunately have to use multiple windows in this program and I don't think CardLayout is going to work because I can't have any buttons constant between the different layouts. So I'm trying to code a button to hide the present JPanel (thePanel) and show a new one (thePlacebo).
I'm trying to hide thePanel in an ActionListener like this:
frame.getContentPane().remove(thePanel);
I thought this would work, but it just freezes my program as soon as I hit the button.
Here's a chunk of the code for context:
public class Reflexology1 extends JFrame{
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
thePlacebo.add(movingButton);
frame.add(thePanel);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame.setVisible(true);
}
// Implement listeners
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
frame.getContentPane().remove(thePanel);
}
}
}
Does anybody know what I might be doing wrong?
After removing components from a container, it goes into the invalidate state. To bring it back to the valid state you have to revalidate and repaint that. In your case you are directly adding/removing components from JFrame so depending on the Java version you can do this :
frame.revalidate(); // For Java 1.7 or above
frame.getContentPane().validate(); // For Java 1.6 or below
frame.repaint();
Here is one working example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment
{
private JFrame frame;
private JPanel firstPanel;
private JPanel secondPanel;
private JButton forwardButton;
private JButton backButton;
private void displayGUI()
{
frame = new JFrame("Assignment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.BLUE);
secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.RED);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(firstPanel);
frame.add(secondPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(secondPanel);
frame.add(firstPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
firstPanel.add(forwardButton);
secondPanel.add(backButton);
frame.add(firstPanel);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Assignment().displayGUI();
}
});
}
}
correct way could be (only) by using CardLayout
otherwise have to remove JPanel from container and to call (as last code line and call only one times after all changes for container are done)
.
myJPanelsContainer#revalidate(); // in Java6 for JFrame validate()
myJPanelsContainer#repaint();

Categories