I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.
import java.awt.EventQueue;
public class ExpenseManager {
private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExpenseManager window = new ExpenseManager();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExpenseManager() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
//#SuppressWarnings("unchecked")
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewUser = new JButton("New User");
btnNewUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewUserName.setVisible(true);
txtUserName.setVisible(true);
btnDone.setVisible(true);
}
});
btnNewUser.setBounds(23, 34, 89, 23);
frame.getContentPane().add(btnNewUser);
txtUserName = new JTextField();
txtUserName.setBounds(240, 63, 134, 20);
frame.getContentPane().add(txtUserName);
txtUserName.setVisible(false);
txtUserName.setColumns(10);
lblNewUserName = new JLabel("Enter New UserName");
lblNewUserName.setBounds(240, 38, 134, 14);
lblNewUserName.setVisible(false);
frame.getContentPane().add(lblNewUserName);
btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newUserName = txtUserName.getText();
if(!newUserName.isEmpty())
{
File f = new File("S:/Expense/" + newUserName);
if (f.exists() && f.isDirectory()) {
JOptionPane.showMessageDialog(null, "User already exists");
txtUserName.setText(null);
}
else{
boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
if(!success){
JOptionPane.showMessageDialog(null, "Unable to register");
}else{
JOptionPane.showMessageDialog(null, "User registered Successfully");
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
}
}
});
btnDone.setBounds(240, 103, 89, 23);
btnDone.setVisible(false);
frame.getContentPane().add(btnDone);
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File[] directories = new File("S:/Expense/").listFiles();
for(int i = 0; i < directories.length; i++)
{
dir[i] = directories[i].getName();
}
comboBox.setVisible(true);
}
});
btnLogin.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btnLogin);
comboBox = new JComboBox<Object>(dir);
comboBox.setBounds(24, 138, 72, 20);
comboBox.setSelectedIndex(1);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
}
}
You can use setModel with DefaultComboBoxModel which take an array instead like :
comboBox.setModel(new DefaultComboBoxModel(dir));
Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE).
Review the following, note the comments:
public class ExpenseManager {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ExpenseManager();
} catch (Exception e) { e.printStackTrace(); }
}
});
}
public ExpenseManager() { initialize(); }
private void initialize() {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null); //better use a layout manger
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setBounds(24, 138, 72, 20);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
JButton btn = new JButton("Populate combo");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
}
});
btn.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btn);
frame.setVisible(true);
}
}
EDIT implementation using a layout manager :
private void initialize() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setVisible(false);
frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default
JButton btn = new JButton("Populate combo");
btn.setPreferredSize(new Dimension(150,35));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
frame.pack(); //resize fram to fit the preferred size and layouts
}
});
frame.getContentPane().add(btn, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
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 :)
i´ve been trying to refresh de JTable after inserting data in MySql, but i cant manage to make it work.
The data is filled in the agregar JPanel and saved after clicking a button, checking in the mysql console, the data is added to the database, but when i open the table it doesn´t update unless i restart the program.
This is My code:
public class verTodos extends JPanel {
contactoDAO dao = new contactoDAO();
List<contacto> contactos = dao.getAll();
private JTable table;
public verTodos() {
String[] colName = { "Id", "Nombre", "Apellido", "Telefono",
"Direccion", "Email", "Rubro1", "Rubro2", "Rubro3" };
Object[][] obj = new Object[contactos.size()][10];
for (int i = 0; i < contactos.size(); i++) {
contacto c = contactos.get(i);
obj[i][0] = c.getId();
bj[i][1] = c.getNombre();
obj[i][2] = c.getApellido();
obj[i][3] = c.getTelefono();
obj[i][4] = c.getDireccion();
obj[i][5] = c.getEmail();
obj[i][6] = c.getRubro1();
obj[i][7] = c.getRubro2();
obj[i][8] = c.getRubro3();
setBounds(100, 100, 800, 300);
}
DefaultTableModel contactTableModel = new DefaultTableModel(obj,colName);
table = new JTable(contactTableModel);
setLayout(new BorderLayout(0, 0));
contactTableModel.fireTableDataChanged();
contactTableModel.setColumnIdentifiers(colName);
add(table.getTableHeader(), BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
repaint();
}
}
this is the main screen that contains the JPanels:
public class principal extends JFrame {
JFrame frame = new JFrame();
JPanel container = new JPanel();
CardLayout cl = new CardLayout();
private final JMenuBar menuBar = new JMenuBar();
/.....
.....
private final JMenuItem mntmVerTodos = new JMenuItem("Ver todos");
private final JMenuItem mntmAgregar = new JMenuItem("Agregar");
agregar ag = new agregar();
verTodos ver = new verTodos();
...
...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new principal();
}
});
}
public principal() {
textField.setMaximumSize(new Dimension(300, 500));
textField.setBounds(new Rectangle(0, 0, 30, 0));
textField.setColumns(10);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int X = (screen.width / 2) - (1366 / 2);
int Y = (screen.height / 2) - (720 / 2);
frame.setBounds(X, Y, 1363, 720);
container.setLayout(cl);
ver.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(ver, "ver");
container.add(ag, "ag");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
frame.getContentPane().add(container);
frame.setJMenuBar(menuBar);
menuBar.add(mnNewMenu);
cl.show(container, "ver");
mntmVerTodos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "ver");
}
});
mnContactos.add(mntmVerTodos);
mnContactos.add(mntmAgregar);
mntmModificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "mod");
}
});
menuBar.add(btn);
frame.setVisible(true);
}
}
You need to repopulate your model once the database has been updated. Add a refresh button that when clicked, updates contactTableModel
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();
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I'm getting the following error:
java.lang.NoSuchMethodError: main
Exception in thread "main"
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class SwimCalc extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel Customers;
JTextArea NameTextCustomers, ExistTextCustomers, NameTextContractors,
ExistTextContractors;
public SwimCalc() {
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createCustomers();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Customers", Customers);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE CUSTOMERS */
public JPanel createCustomers() {
Customers = new JPanel();
Customers.setLayout(null);
NameTextCustomers = new JTextArea();
NameTextCustomers.setBounds(10, 10, 350, 150);
NameTextCustomers.setLineWrap(true);
Customers.add(NameTextCustomers);
JButton Exit = new JButton("Exit");
Exit.setBounds(30, 170, 80, 20);
Exit.addActionListener(this);
Exit.setBackground(Color.white);
Customers.add(Exit);
JButton AddCustomers = new JButton("Add Customer");
AddCustomers.setBounds(130, 170, 120, 20);
AddCustomers.setBackground(Color.white);
Customers.add(AddCustomers);
JButton Refresh = new JButton("Refresh");
Refresh.setBounds(260, 170, 80, 20);
Refresh.setBackground(Color.white);
Customers.add(Refresh);
ExistTextCustomers = new JTextArea();
ExistTextCustomers.setBounds(10, 200, 350, 60);
ExistTextCustomers.setLineWrap(true);
Customers.add(ExistTextCustomers);
final JTextArea custArea = new JTextArea(6, 30);
final JTextArea custMessage = null;
AddCustomers.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Customer("Customer");
}
});
Customers.add(custArea);
Customers.add(AddCustomers);
Customers.add(Refresh);
Customers.add(custMessage);
Refresh.setMnemonic('R');
Refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
custMessage.setText("");
try {
File custOpen = new File("customer.txt");
FileReader custAreaIn = new FileReader(custOpen);
custArea.read(custAreaIn, custOpen.toString());
custMessage.setText("The file exists and can be read from.");
} catch (IOException e3) {
custMessage.setText("The file could not be read. "
+ e3.getMessage());
}
}
});
return Customers;
}
class Customer extends JFrame {
private String[] states = { "AL", "AK", "AZ", "AR", "CA", "CO", "CT",
"DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA",
"ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH",
"NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" };
private JComboBox StateList = new JComboBox(states);
private JTextField NameText = new JTextField(25);
private JTextField AddressText = new JTextField(25);
private JTextField CityText = new JTextField(25);
private JTextField ZipText = new JTextField(9);
private JTextField PhoneText = new JTextField(10);
private JTextField PopMessageText = new JTextField(30);
private static final long serialVersionUID = 1L;
private AddCustButtonHandler addCusHandler = new AddCustButtonHandler();
public Customer(String who) {
popUpWindow(who);
}
public void popUpWindow(final String who) {
final JFrame popWindow;
popWindow = new JFrame(who);
popWindow.setSize(425, 350);
popWindow.setLocation(100, 100);
popWindow.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = new Container();
popWindow.add(c);
c.setLayout(new FlowLayout());
JPanel one = new JPanel();
JPanel two = new JPanel();
JPanel three = new JPanel();
JPanel four = new JPanel();
JPanel five = new JPanel();
JPanel six = new JPanel();
one.add(new JLabel(who + " Name "));
one.add(NameText);
two.add(new JLabel("Address "));
two.add(AddressText);
three.add(new JLabel("City "));
three.add(CityText);
four.add(new JLabel("State "));
StateList.setSelectedIndex(0);
four.add(StateList);
four.add(new JLabel("ZIP"));
four.add(ZipText);
four.add(new JLabel("Phone"));
four.add(PhoneText);
JButton addwho = new JButton("Add " + who);
addwho.setMnemonic('A');
JButton close = new JButton("Close");
close.setMnemonic('C');
JButton deleteFile = new JButton("Delete File");
deleteFile.setMnemonic('D');
five.add(addwho);
five.add(close);
five.add(deleteFile);
PopMessageText.setEditable(false);
PopMessageText.setHorizontalAlignment(JTextField.CENTER);
six.add(PopMessageText);
c.add(one);
c.add(two);
c.add(three);
c.add(four);
c.add(five);
c.add(six);
deleteFile.setToolTipText("Delete File");
addwho.setToolTipText("Add " + who);
close.setToolTipText("Close");
if (who == "Customer")
addwho.addActionListener(addCusHandler);
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
NameText.setText("");
AddressText.setText("");
CityText.setText("");
ZipText.setText("");
PhoneText.setText("");
PopMessageText.setText("");
popWindow.dispose();
}
});
deleteFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PopMessageText.setText("");
if (who == "Customer") {
File file = new File("Customer.txt");
boolean cusFileDeleted = file.delete();
if (cusFileDeleted) {
PopMessageText.setText("Customer file has been deleted");
} else {
PopMessageText
.setText("There was an erron in deleting file");
}
}
}
});
}
class AddCustButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent addCusHandler) {
int StateIndex;
try {
File file = new File("Customer.txt");
boolean success = file.createNewFile();
if (success) {
PopMessageText
.setText("Customer.txt file created file added");
} else if (file.canWrite()) {
PopMessageText
.setText("Writing data to Customer.txt, file added");
} else {
PopMessageText.setText("Cannot create file: Customer.txt");
}
try {
FileWriter fileW = new FileWriter("Customer.txt", true);
fileW.write(NameText.getText());
fileW.write(",");
fileW.write(AddressText.getText());
fileW.write(",");
fileW.write(CityText.getText());
fileW.write(",");
StateIndex = StateList.getSelectedIndex();
fileW.write(states[StateIndex]);
fileW.write(",");
fileW.write(ZipText.getText());
fileW.write(",");
fileW.write(PhoneText.getText());
fileW.write("\r\n");
fileW.close();
PopMessageText.setText("A new Customer has been added!");
FileReader fileR = new FileReader("Customer.txt");
BufferedReader buffIn = new BufferedReader(fileR);
String textData = buffIn.readLine();
buffIn.close();
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage(), "ERROR",
2);
}
NameText.setText("");
AddressText.setText("");
CityText.setText("");
ZipText.setText("");
PhoneText.setText("");
} catch (IOException e1) {
}
}
}
public void actionPerformed(ActionEvent event) {
}
private void Exit_pressed() {
System.exit(0);
}
public void main(String[] args) {
JFrame frame = new SwimCalc();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
}
}
The error:
java.lang.NoSuchMethodError: main
Exception in thread "main"
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args){
JFrame frame = new SwimCalc();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
main needs to be a static method.
public static void main(String[] args){
JFrame frame = new SwimCalc();
frame.setSize(380, 350);
frame.setVisible(true);
}
Also, the main method should be in the SwimCalc class or some other top-level class. Move the method to be within the SwimCalc class (not in your Customer class) and use java SwimCalc to invoke it. You can't declare main in an inner class.
It looks your main method is actually inside your actionPerformed method. You obviously cannot do this. The declaration needs to be in your SwimCalc class. Is that craziness your actual code that you are trying to run? You've got braces and stray parentheses all over the place, no indentation; if you just clean up your code the problem will be a lot easier to find.
and
public void main(String[] args){
should be
public static void main(String[] args){
There's also nonsense like this: } );. You have so many syntax errors...
Yes the signature should be
public static void main(String[] args)
Even if the args is missed eclipse throws this error.
public **static** void main(String[] args){
Main method must be public static
public static void main(String[] args)
main() must be static. The complete signature is:
public static void main(String[] args)
You main method needs to be static. This should be the signature:
public static void main(String[] args)
It should be
public static void main(String[] args){
instead of public void main...