How to make an image move using the keyboard in java? - java

I have a maze that I need to get a ball to move through, but I don't know what code I need to use to move the image of the ball around the maze.
I have been given a hint that I need to swap images round.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBallMaze extends JFrame implements ActionListener
{
//Below is where I have declared all the different objects I have used throughout my program
private JButton buttonRight, buttonLeft, buttonUp, buttonDown, buttonTL, buttonTR, buttonBL, buttonBR, buttonCenter, optionOne, optionTwo, optionThree, optionExit, scenarioAct, scenarioRun, scenarioReset, compassPH;
private JButton [] game = new JButton [208];
private JPanel panelCentre, panelRight, panelBottom, buttonPanel, compassPanel, optionsPanel, selectionPanel, panelAct, panelRun, panelReset, panelSlider;
private JTextField optionTF, squareTF, directionTF;
private JLabel option, square, direction, compassDirection;
private JSlider speedSlider;
private String firstOption = "1", secondOption = "2", thirdOption = "3", upDirection = "North", rightDirection = "East", downDirection = "South", leftDirection = "West";
private int i;
private int[] map = new int[]
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
3,1,3,3,3,1,3,3,3,1,3,3,3,3,3,3,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
3,3,1,3,3,3,1,3,3,3,3,1,3,3,3,3,
4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
};
final ImageIcon iconCompassNorth = new ImageIcon("north.jpg");
final ImageIcon iconCompassWest = new ImageIcon("west.jpg");
final ImageIcon iconCompassSouth = new ImageIcon("south.jpg");
final ImageIcon iconCompassEast = new ImageIcon("east.jpg");
ImageIcon iconReset = new ImageIcon("Reset.jpg");
ImageIcon iconRun = new ImageIcon("Run.jpg");
ImageIcon iconAct = new ImageIcon("Act.jpg");
ImageIcon iconSand, iconWhite, iconBall, iconEnd;
public CBallMaze(String title) {
super(title);
}
public static void main(String[] args)
{
CBallMaze cBallMaze = new CBallMaze("CBallMaze Ball Maze Application");
cBallMaze.setSize(775, 650);
cBallMaze.createGUI();
cBallMaze.setVisible(true);
}
private void createGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new BorderLayout() );
//Panels
panelCentre = new JPanel();
panelCentre.setPreferredSize(new Dimension(625, 450));
panelCentre.setBackground(Color.BLACK);
window.add(panelCentre);
panelCentre.setLayout(new GridLayout(13, 16));
panelRight = new JPanel();
panelRight.setPreferredSize(new Dimension(180, 450));
panelRight.setBackground(Color.WHITE);
window.add(panelRight, BorderLayout.EAST);
optionsPanel = new JPanel();
optionsPanel.setPreferredSize(new Dimension(150, 100));
optionsPanel.setBackground(Color.WHITE);
panelRight.add(optionsPanel, BorderLayout.EAST);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(175, 100));
buttonPanel.setBackground(Color.WHITE);
panelRight.add(buttonPanel, BorderLayout.EAST);
selectionPanel = new JPanel();
selectionPanel.setPreferredSize(new Dimension(175, 150));
selectionPanel.setBackground(Color.WHITE);
panelRight.add(selectionPanel, BorderLayout.EAST);
ImageIcon cw = new ImageIcon("west.jpg");
compassPanel = new JPanel();
compassPanel.setPreferredSize(new Dimension(175, 300));
compassPanel.setBackground(Color.WHITE);
panelRight.add(compassPanel, BorderLayout.EAST);
panelBottom = new JPanel();
panelBottom.setPreferredSize(new Dimension(875, 50));
panelBottom.setBackground(Color.WHITE);
window.add(panelBottom, BorderLayout.SOUTH);
panelAct = new JPanel();
panelAct.setPreferredSize(new Dimension(125, 40));
panelAct.setBackground(Color.WHITE);
panelBottom.add(panelAct, BorderLayout.SOUTH);
panelRun = new JPanel();
panelRun.setPreferredSize(new Dimension(125, 40));
panelRun.setBackground(Color.WHITE);
panelBottom.add(panelRun, BorderLayout.SOUTH);
panelReset = new JPanel();
panelReset.setPreferredSize(new Dimension(125, 40));
panelReset.setBackground(Color.WHITE);
panelBottom.add(panelReset, BorderLayout.SOUTH);
panelSlider = new JPanel();
panelSlider.setPreferredSize(new Dimension(200, 40));
panelSlider.setBackground(Color.WHITE);
panelBottom.add(panelSlider, BorderLayout.SOUTH);
//Displays
option = new JLabel("Option: ");
optionsPanel.add(option, BorderLayout.LINE_START);
option.setEnabled(true);
option.setForeground(Color.BLACK);
option.setHorizontalAlignment(JLabel.LEFT);
optionTF = new JTextField("1");
optionsPanel.add(optionTF, BorderLayout.LINE_END);
optionTF.setEnabled(true);
optionTF.setPreferredSize(new Dimension(50, 25));
optionTF.setHorizontalAlignment(JTextField.CENTER);
square = new JLabel("Square: ");
optionsPanel.add(square, BorderLayout.LINE_START);
square.setEnabled(true);
square.setForeground(Color.BLACK);
square.setHorizontalAlignment(JLabel.LEFT);
squareTF = new JTextField("");
optionsPanel.add(squareTF, BorderLayout.LINE_END);
squareTF.setEnabled(true);
squareTF.setPreferredSize(new Dimension(50, 25));
squareTF.setHorizontalAlignment(JTextField.CENTER);
direction = new JLabel("Direction: ");
optionsPanel.add(direction, BorderLayout.LINE_START);
direction.setEnabled(true);
direction.setForeground(Color.BLACK);
direction.setHorizontalAlignment(JLabel.LEFT);
directionTF = new JTextField("Still");
optionsPanel.add(directionTF, BorderLayout.LINE_END);
directionTF.setEnabled(true);
directionTF.setPreferredSize(new Dimension(50, 25));
directionTF.setHorizontalAlignment(JTextField.CENTER);
//buttons
buttonTL = new JButton("");
buttonPanel.add(buttonTL);
buttonTL.setPreferredSize(new Dimension(45, 25));
buttonTL.setEnabled(false);
buttonUp = new JButton("^");
buttonPanel.add(buttonUp);
buttonUp.setPreferredSize(new Dimension(45, 25));
buttonUp.addActionListener(this);
buttonUp.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(upDirection);
compassDirection.setIcon(iconCompassNorth);
}
});
buttonTR = new JButton("");
buttonPanel.add(buttonTR);
buttonTR.setPreferredSize(new Dimension(45, 25));
buttonTR.setEnabled(false);
buttonLeft = new JButton("<");
buttonPanel.add(buttonLeft);
buttonLeft.setPreferredSize(new Dimension(45, 25));
buttonLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(leftDirection);
compassDirection.setIcon(iconCompassWest);
}
});
buttonCenter = new JButton("");
buttonPanel.add(buttonCenter);
buttonCenter.setPreferredSize(new Dimension(45, 25));
buttonCenter.setEnabled(false);
buttonRight = new JButton(">");
buttonPanel.add(buttonRight);
buttonRight.setPreferredSize(new Dimension(45, 25));
buttonRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(rightDirection);
compassDirection.setIcon(iconCompassEast);
}
});
buttonBL = new JButton("");
buttonPanel.add(buttonBL);
buttonBL.setPreferredSize(new Dimension(45, 25));
buttonBL.setEnabled(false);
buttonDown = new JButton("v");
buttonPanel.add(buttonDown);
buttonDown.setPreferredSize(new Dimension(45, 25));
buttonDown.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
directionTF.setText(downDirection);
compassDirection.setIcon(iconCompassSouth);
}
});
buttonBR = new JButton("");
buttonPanel.add(buttonBR);
buttonBR.setPreferredSize(new Dimension(45, 25));
buttonBR.setEnabled(false);
optionOne = new JButton("Option One");
selectionPanel.add(optionOne);
optionOne.setPreferredSize(new Dimension(125, 25));
optionOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(firstOption);
}
});
optionTwo = new JButton("Option Two");
selectionPanel.add(optionTwo);
optionTwo.setPreferredSize(new Dimension(125, 25));
optionTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(secondOption);
}
});
optionThree = new JButton("Option Three");
selectionPanel.add(optionThree);
optionThree.setPreferredSize(new Dimension(125, 25));
optionThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
optionTF.setText(thirdOption);
}
});
optionExit = new JButton("Exit");
selectionPanel.add(optionExit);
optionExit.setPreferredSize(new Dimension(125, 25));
scenarioAct = new JButton("Act");
scenarioAct.setIcon(iconAct);
panelAct.add(scenarioAct);
scenarioAct.addActionListener(this);
scenarioRun = new JButton("Run");
scenarioRun.setIcon(iconRun);
panelRun.add(scenarioRun);
scenarioRun.addActionListener(this);
scenarioReset = new JButton("Reset");
scenarioReset.setIcon(iconReset);
panelReset.add(scenarioReset);
scenarioReset.addActionListener(this);
JSlider speedSlider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
speedSlider.setMajorTickSpacing(10);
speedSlider.setMinorTickSpacing(5);
speedSlider.setPaintTicks(true);
speedSlider.setBackground(Color.WHITE);
speedSlider.setLabelTable(speedSlider.createStandardLabels(10));
panelSlider.add(speedSlider);
compassDirection = new JLabel();
compassPanel.add(compassDirection);
try
{
iconSand = new ImageIcon("sand.jpg");
}
catch (Exception e)
{
System.err.println("Sand Icon "+e);
}
try
{
iconBall = new ImageIcon("sand60x60.png");
}
catch (Exception e)
{
System.err.println("Ball Icon "+e);
}
try
{
iconWhite = new ImageIcon("white32x32.jpg");
}
catch (Exception e)
{
System.err.println("White Icon "+e);
}
try
{
iconEnd = new ImageIcon("sandstone.jpg");
}
catch (Exception e)
{
System.err.println("End Icon"+e);
}
for (i=0;i<208;i++)
{
game[i] = new JButton ();
if(map[i]==1)
{
game[i].setIcon(iconSand);
}
if(map[i]==2)
{
game[i].setIcon(iconBall);
}
if(map[i]==3)
{
game[i].setIcon(iconWhite);
}
if(map[i]==4)
{
game[i].setIcon(iconEnd);
}
game[i].setBorder(null);
game[i].setPreferredSize(new Dimension(32, 32));
game[i].addActionListener(this);
panelCentre.add(game[i]);
}
}
public void actionPerformed(ActionEvent arg0)
{
}
}

Try this (works for me):
After this line panelCentre.add(game[i]); enter this:
game[i].addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
System.out.println("right...");
break;
case KeyEvent.VK_LEFT:
System.out.println("left...");
break;
case KeyEvent.VK_DOWN:
System.out.println("down...");
break;
case KeyEvent.VK_UP:
System.out.println("up...");
}
}
});
This should print out the direction you typed with the arrow keys.

Here is the answer to the question
How to move the ball in the maze
https://gist.github.com/ad78d37918de6320733b
Note that you should use an own KeyEventDispatcher because otherwise you would have to attach the KeyListener to ALL components in your WHOLE GUI (see this post)
Anyway, as #chris pointed out, a ball object and another data structure than array would make your assignment easier :)

Related

Overlay a picture over background picture

I'm making a street fighter game in java, I have all the background pictures finished, and I'm trying to add the characters onto the background, but in the output the character picture keeps appearing next to the background instead of on top of it. I want the character to appear on top of the background, just like a normal street fighter game.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.Border;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class CastleFighter extends JFrame {
Image image;
public static void main(String[] args) {
CastleFighter angela = new CastleFighter();
angela.runIt();
}
public void runIt() {
final JFrame frame = new JFrame("Castle Fighter");
frame.setSize(500, 477);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pa = new JPanel();
JButton ba1 = new JButton("Start");
ba1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
final JFrame frame2 = new JFrame("Menu");
frame2.setDefaultCloseOperation(HIDE_ON_CLOSE);
JPanel pa2 = new JPanel();
frame2.add(pa2);
ImageIcon iii = new ImageIcon(this.getClass().getResource("fight.gif"));
JLabel imageLabel2 = new JLabel();
imageLabel2.setIcon(iii);
pa2.add(imageLabel2, java.awt.BorderLayout.CENTER);
frame2.setVisible(true);
frame2.pack();
frame2.requestFocus();
imageLabel2.setLayout(new GridLayout(3, 0));
JButton ba2 = new JButton("How to play");
ba2.setFont(new Font("Merriweather", Font.PLAIN, 28));
imageLabel2.add(ba2, BorderLayout.SOUTH);
ba2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame3 = new JFrame("How to play");
frame3.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa3 = new JPanel();
frame3.add(pa3);
JButton ba5 = new JButton("Return to menu");
ba5.setFont(new Font("Merriweather", Font.PLAIN, 28));
ba5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame3.dispose();
frame2.setVisible(true);
}
});
pa3.setLayout(new BorderLayout());
pa3.add(ba5, BorderLayout.SOUTH);
ImageIcon iiiii = new ImageIcon(this.getClass().getResource("ezgif.com-crop-7.gif"));
JLabel imageLabel4 = new JLabel();
imageLabel4.setIcon(iiiii);
pa3.add(imageLabel4, java.awt.BorderLayout.CENTER);
frame3.setVisible(true);
frame3.pack();
frame3.requestFocus();
}
});
JButton ba3 = new JButton("Start game");
ba3.setFont(new Font("RussoOne", Font.PLAIN, 28));
imageLabel2.add(ba3, BorderLayout.CENTER);
ba3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame4 = new JFrame("Level one");
frame4.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa4 = new JPanel();
frame4.add(pa4);
ImageIcon iiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-7.gif"));
JLabel imageLabel3 = new JLabel();
imageLabel3.setIcon(iiii);
pa4.add(imageLabel3, java.awt.BorderLayout.CENTER);
ImageIcon i14 = new ImageIcon(this.getClass().getResource("fightercharacter.gif"));
JLabel imageLabel14 = new JLabel();
imageLabel14.setIcon(i14);
pa4.add(imageLabel14, java.awt.BorderLayout.NORTH);
JButton ba6 = new JButton("menu");
ba6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
frame2.setVisible(true);
}
});
pa4.add(ba6);
JButton ba7 = new JButton("Level two");
ba7.setSize(400, 200);
pa4.add(ba7);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
final JFrame frame6 = new JFrame("Level two");
frame6.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame6.setVisible(true);
JPanel pa6 = new JPanel();
frame6.add(pa6);
ImageIcon iiiiiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-6.gif"));
JLabel imageLabel6 = new JLabel();
imageLabel6.setIcon(iiiiiii);
pa6.add(imageLabel6, BorderLayout.CENTER);
frame6.pack();
frame6.requestFocus();
JButton ba7 = new JButton("menu");
pa6.add(ba7, BorderLayout.SOUTH);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame2.setVisible(true);
}
});
JButton ba9 = new JButton("Level one");
pa6.add(ba9, BorderLayout.SOUTH);
ba9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame4.setVisible(true);
}
});
frame6.setVisible(true);
frame6.pack();
frame6.requestFocus();
}
});
frame4.setVisible(true);
frame4.pack();
frame4.requestFocus();
}
});
JButton ba4 = new JButton("Quit game");
ba4.setFont(new Font("MerriWeather", Font.PLAIN, 28));
imageLabel2.add(ba4, BorderLayout.WEST);
ba4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame2.requestFocus();
ba2.setOpaque(false);
ba2.setContentAreaFilled(false);
ba2.setBorderPainted(false);
ba2.setForeground(Color.WHITE);
ba3.setOpaque(false);
ba3.setContentAreaFilled(false);
ba3.setBorderPainted(false);
ba3.setForeground(Color.WHITE);
ba4.setOpaque(false);
ba4.setContentAreaFilled(false);
ba4.setBorderPainted(false);
ba4.setForeground(Color.WHITE);
}
});
ba1.setPreferredSize(new Dimension(100, 100));
ba1.setFont(new Font("RussoOne", Font.PLAIN, 28));
ba1.setBackground(Color.BLUE);
ba1.setOpaque(true);
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(ba1, BorderLayout.SOUTH);
ImageIcon ii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-2.gif"));
JLabel imageLabel = new JLabel();
imageLabel.setIcon(ii);
pa.add(imageLabel, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
frame.requestFocus();
}
}

Cant access global variable in actionPeformed method in java Swing application

I have application where on Jbutton click i create new JFrame with its own class and import file
When i read file i passed that file to method of my MainGui class where i parse data and store it in array of objects which is global field.
When i click on another button from MainGui, i cant access that array of objets and none of its fields(i get nullPointerException)
Here is my code:
MainGui Class
public class MainGui implements ActionListener {
private JFrame frame;
private JPanel panel;
GrupaArtikala[] objektiArtikli; // ARRAY OF OBJECTS
JPanel centerPanel = new JPanel(new BorderLayout());
private final int MAX_TABLES = 8;
JButton buttonImport;
JButton [] buttonsTables = new JButton[MAX_TABLES];
String tables[] = {
"Grupa artikala",
"Osnovna mera",
"Jedinica mere",
"Naknada",
"Popust",
"Artikal",
"Normativ",
"Normativ stavka",
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGui window = new MainGui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createAndShowPodesavanja() {
GuiFileChooser guiPodesavanja= new GuiFileChooser(); // HERE I CREATE NEW FRAME
guiPodesavanja.initialize();
guiPodesavanja.setVisible(true);
// this.setVisible(false);
}
public MainGui() {
initialize();
}
public void pars(String file) {
try {
String content = new String(Files.readAllBytes(Paths.get(file)));
int startArtikitag = content.indexOf(":ISSI");
int endArticalTag = content.indexOf("#TABLENAME:OSNOVNA_MJERA");
String gupaArtikalaString = content.substring(startArtikitag + 5, endArticalTag - 15);
System.out.println(gupaArtikalaString);
String[] lines =gupaArtikalaString.split(System.lineSeparator());
objektiArtikli = new GrupaArtikala[lines.length];
for(int i = 1; i < lines.length; i++) {
objektiArtikli[i] = new GrupaArtikala(lines[i]); // HERE I INITALIAZE ARRAY OF OBJECTS
}
System.out.println("rec u konstruktoru lokalno " + objektiArtikli[1].getId());
System.out.println("rec u gobalno" + objektiArtikli[1].getId());
// HERE I HAVE OUTPUT
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initialize();
}
private void initialize() {
frame = new JFrame("FreshPos baza podataka");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Main paneel
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder( BorderFactory.createEmptyBorder(10,10,10,10) );
frame.getContentPane().add(panel);
//West panel;
JPanel panelWest = new JPanel(new GridLayout(14,0,0,2));
panelWest.setBorder( BorderFactory.createEmptyBorder(200,0,10,10) );
panel.add(panelWest, BorderLayout.WEST);
for (int i = 0; i < MAX_TABLES; i++) {
buttonsTables[i] = new JButton(tables[i]);
//buttonsTables[i].setMaximumSize(new Dimension(Integer.MAX_VALUE, buttonsTables[i].getMinimumSize().height));
//buttonsTables[i].setPreferredSize(new Dimension(200,400));
panelWest.add(buttonsTables[i]);
}
buttonsTables[0].addActionListener(this); // HERE I CLICK ON BUTTON!!
//North panel;
JPanel northPanel = new JPanel(); // Donji layout za dugmice
northPanel.setBorder( BorderFactory.createEmptyBorder(0,0,0,0) );
panel.add(northPanel, BorderLayout.NORTH);
//northPanel.setBackground(Color.green);
buttonImport = new JButton("Importuj datoteku");
buttonImport.setPreferredSize(new Dimension(180,40));
northPanel.add(buttonImport, BorderLayout.WEST);
buttonImport.addActionListener(this);
JButton ButtonRecord = new JButton("Snimi datoteku");
ButtonRecord.setPreferredSize(new Dimension(180,40));
northPanel.add(ButtonRecord, BorderLayout.WEST);
}
public void showGrupaArtikala () {
centerPanel.removeAll();
centerPanel.updateUI();
centerPanel.setBackground(Color.GRAY);
panel.add(centerPanel, BorderLayout.CENTER);
JPanel southInCentral = new JPanel(); // Donji layout za dugmice
centerPanel.add(southInCentral, BorderLayout.SOUTH);
JButton buttonDodaj = new JButton("Dodaj");
//buttonDodaj.setLocation(100, 100);
buttonDodaj.setPreferredSize(new Dimension(180,40));
southInCentral.add(buttonDodaj);
JButton buttonIzmeni = new JButton("Izmeni");
buttonIzmeni.setPreferredSize(new Dimension(180,40));
southInCentral.add(buttonIzmeni);
JButton butonObrisi = new JButton("Obrisi");
butonObrisi.setPreferredSize(new Dimension(180,40));
southInCentral.add(butonObrisi);
// Center layout in central panel
JPanel centralInCentral = new JPanel(); //
centerPanel.add(centralInCentral);
// Jtable
String[] columnNames = {"ID,",
"SIFRA",
"NAZIV",
"IKONA_ID"};
Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
};
JTable table = new JTable(data, columnNames);
//JTable(Object[][] rowData, Object[] columnNames)
JScrollPane scrollPane = new JScrollPane(table);
centerPanel.add(scrollPane);
panel.repaint();
panel.revalidate();
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonsTables[0]) {
System.out.println("String here "+ objektiArtikli[1].getId()); // HERE OUTPUT IS NULL
showGrupaArtikala();
} else if (e.getSource() == buttonImport) {
System.out.println("aa");
createAndShowPodesavanja();
}
}
}
GuiFileChooser Class
public class GuiFileChooser {
private JFrame frame;
JTextField jEditText;
public GuiFileChooser () {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiFileChooser window = new GuiFileChooser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void fileChoose(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
int i=chooser.showOpenDialog(frame);
if(i==JFileChooser.APPROVE_OPTION){
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
MainGui m = new MainGui();
m.pars(filename); // HERE I CALL pars(filename) in MainGui method
jEditText.setText(filename);
}
}
void initialize() {
frame = new JFrame();
frame.setTitle("Dodaj datoteku");
frame.setBounds(750, 350, 460, 150); // top
//Dimension d = new Dimension(440, 200);
// Dimension d1 = new Dimension(451, 451);
frame.setResizable(false);
//frame.setPreferredSize(d);
//frame.setMinimumSize(d);
// frame.setMaximumSize(d1);
// frame.setSize(450, 450);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton lblNaziv = new JButton("Izaberite datoteku..");
lblNaziv.setBounds(10 ,10, 160, 25); // horizontalna margina , vertikalna margina , visina, duzina
lblNaziv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileChoose(evt);
}
});
frame.getContentPane().add(lblNaziv);
jEditText = new JTextField();
jEditText.setBounds(180 ,10, 250, 25); // horizontalna margina , vertikalna margina , visina, duzina
frame.getContentPane().add(jEditText);
JButton buttonOk = new JButton("OK");
buttonOk.setBounds(180,50, 100, 30); // horizontalna margina , vertikalna margina ,
frame.getContentPane().add(buttonOk);
buttonOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
frame.dispose();
}
});
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
}

JPanel on CardLayout Swing Java

I am new to Java and I am making a navigation through CardLayout in Swing. Basically I have two buttons on a JFrame and when I click on one button it should go to card 1 where I have kept two buttons on JPanel, card1 and when I click on another button it should go to card 2 where I have kept a JTextField on panel card2. But it is not happening.
Can anyone fix it?
My code is as below.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutTest extends JFrame implements ActionListener {
JFrame f;
JButton b;
JButton c;
JPanel panel;
JPanel cards;
JPanel card1;
JPanel card2;
CardLayout card;
Container pane;
final String card1Text = "One";
final String card2Text = "Two";
CardLayoutTest() {
}
public void passBtn() {
f=new JFrame("Card Layout Test");
card1 = new JPanel();
card1.add(new JButton("Button 1 - Card 1"));
card1.add(new JButton("Button 2 - Card 1"));
card1.setBackground(new Color(255,0,0));
card2 = new JPanel();
card2.add(new JTextField("TextField on Card 2", 20));
card2.setBackground(new Color(0,255,0));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, card1Text);
cards.add(card2, card2Text);
b = new JButton("Page 1");
b.setBounds(50,50,70,30);
b.setBackground(Color.red);
c = new JButton("Page 2");
c.setBounds(50,80,70,30);
c.setBackground(Color.blue);
pane = f.getContentPane();
pane.add(cards, BorderLayout.CENTER);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card1, card1Text);
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card2, card2Text);
}
});
f.add(b); f.add(c); f.add(panel); f.add(cards);
}
public static void main(String[] args) {
new CardLayoutTest();
}
}
Try:
card = new CardLayout();
cards = new JPanel(card);
instead of cards = new JPanel(new CardLayout());
UPDATE
public class CardLayoutTest extends JFrame {
JButton b;
JButton c;
JPanel cards;
JPanel card1;
JPanel card2;
CardLayout card;
final String card1Text = "One";
final String card2Text = "Two";
CardLayoutTest() {
super();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
passBtn();
}
public void passBtn() {
card1 = new JPanel();
card1.setBackground(new Color(255,0,0));
card2 = new JPanel();
card2.add(new JTextField("TextField on Card 2", 20));
card2.setBackground(new Color(0, 255, 0));
//Create the panel that contains the "cards".
card = new CardLayout();
cards = new JPanel(card);
cards.add(card1, card1Text);
cards.add(card2, card2Text);
b = new JButton("Page 1");
b.setBounds(50, 50, 70, 30);
b.setBackground(Color.red);
card1.add(b);
c = new JButton("Page 2");
c.setBounds(50, 80, 70, 30);
c.setBackground(Color.blue);
card1.add(c);
add(cards);
card.show(cards, card1Text);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
card.show(cards, card1Text);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
card.show(cards, card2Text);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
public static void main(String[] args) {
CardLayoutTest cardLayoutTest = new CardLayoutTest();
cardLayoutTest.setVisible(true);
}
}

Java insertIcon multiple times in a text pane

I'm writing a chat program in Java. I made a section for smileys. I managed to print the smileys on a text pane every time its clicked but when I click on the same smiley more than once it only prints it once. Any help?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SmileyTesterGUI extends JFrame {
JPanel main = new JPanel();
JPanel south = new JPanel();
JPanel messageCenter = new JPanel();
JPanel smileysNorth = new JPanel();
JTextField text;
JTextPane tPane;
Icon happy;
Icon smile;
Icon tongue;
Icon veryHappy;
Icon wink;
Icon laugh;
Icon sad;
Icon verySad;
Icon cry;
int number = 0;
boolean check = true;
public SmileyTesterGUI() {
super("Smileys");
add(main);
main.setLayout(new BorderLayout());
main.add(south, BorderLayout.SOUTH);
south.setLayout(new BorderLayout());
south.add(messageCenter, BorderLayout.CENTER);
south.add(smileysNorth, BorderLayout.NORTH);
// textpane panel
tPane = new JTextPane();
JScrollPane sPane = new JScrollPane(tPane);
main.add(sPane);
tPane.setEditable(false);
// smileysPanel
smileysNorth.setLayout(new GridLayout(1, 0));
JButton smiley1 = new JButton();
JButton smiley2 = new JButton();
JButton smiley3 = new JButton();
JButton smiley4 = new JButton();
JButton smiley5 = new JButton();
JButton smiley6 = new JButton();
JButton smiley7 = new JButton();
JButton smiley8 = new JButton();
JButton smiley9 = new JButton();
smileysNorth.add(smiley1);
smileysNorth.add(smiley2);
smileysNorth.add(smiley3);
smileysNorth.add(smiley4);
smileysNorth.add(smiley5);
smileysNorth.add(smiley6);
smileysNorth.add(smiley7);
smileysNorth.add(smiley8);
smileysNorth.add(smiley9);
// set smileys(icon) to each button - pathed from personal directory
happy = new ImageIcon(getClass().getResource("smileys/Smile1.png"));
smiley1.setIcon(happy);
smile = new ImageIcon(getClass().getResource("smileys/Smile2.png"));
smiley2.setIcon(smile);
tongue = new ImageIcon(getClass().getResource("smileys/Smile3.png"));
smiley3.setIcon(tongue);
veryHappy = new ImageIcon(getClass().getResource("smileys/Smile4.png"));
smiley4.setIcon(veryHappy);
wink = new ImageIcon(getClass().getResource("smileys/Smile5.png"));
smiley5.setIcon(wink);
laugh = new ImageIcon(getClass().getResource("smileys/Smile6.png"));
smiley6.setIcon(laugh);
sad = new ImageIcon(getClass().getResource("smileys/Smile7.png"));
smiley7.setIcon(sad);
verySad = new ImageIcon(getClass().getResource("smileys/Smile8.png"));
smiley8.setIcon(verySad);
cry = new ImageIcon(getClass().getResource("smileys/Smile9.png"));
smiley9.setIcon(cry);
// smileys print on the textpane
smiley1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(happy);
}
});
smiley2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(smile);
}
});
smiley3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(tongue);
}
});
smiley4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(veryHappy);
}
});
smiley5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(wink);
}
});
smiley6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(laugh);
}
});
smiley7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(sad);
}
});
smiley8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(verySad);
}
});
smiley9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(cry);
}
});
// messagePanel
messageCenter.setLayout(new BorderLayout());
text = new JTextField();
JButton send = new JButton("Send");
messageCenter.add(text);
messageCenter.add(send, BorderLayout.EAST);
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
setLocation(500, 0);
setSize(600, 250);
}
public void sendMessage() {
String a = text.getText();
//
// if(a){
// tPane.setText(a);
// tPane.getText();
// }
if (a.contains(":D")) {
tPane.insertIcon(veryHappy);
} else if (a.contains(":)")) {
tPane.insertIcon(happy);
} else if (a.contains(":(")) {
tPane.insertIcon(sad);
}
// text.setText(null);
// text.requestFocus();
}
public static void main(String[] args) {
new SmileyTesterGUI().setVisible(true);
}
}
That is because you cannot add the same ImageIcon to the JTextPane more then once.
You can create the ImageIcons dynamically in the ActionListener, every time a smiley is clicked create a new ImageIcon
smiley2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource("smileys/Smile2.png")));
}
});

java JFame will not work when started by actionPerformed

I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}

Categories

Resources