public void init(GUI gui){
// the class extends Jframe
gui.setSize(1024, 700);
gui.setPreferredSize(new Dimension(1024, 700));
gui.setResizable(false);
gui.setLocationRelativeTo(null);
gui.setTitle("Student Management System");
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
Admin_AllStudents_pnl=new JLayeredPane();
Admin_AllStudents_pnl.setSize(1024,700);
Admin_AllStudents_pnl.setLayout(null);
Admin_AllStudents_pnl.setVisible(false);
Admin_AllStudents_pnl.setOpaque(true);
// Admin_AllStudents_pnl.setBackground(Color.white);
String col[]={"ID","Name","Password","Cell","Adress"};
DefaultTableModel tablemodel=new DefaultTableModel(col,0);
All_Students=new JTable(tablemodel);
view_all=new JButton("View_All");
Admin_AllStudents_pnl.add(view_all);
view_all.setBorder(null);
view_all.setBounds(10,10,view_all.getPreferredSize().width,view_all.getPreferredSize().height);
view_all.addActionListener(new ActionListener(){
#Override
// Student and admin are both classes s gets an array list from the admin of all //the students.
//i need to display them in a table format so using for loop.
public void actionPerformed(ActionEvent ae) {
ArrayList<Student> s=new ArrayList<>();
s=admin.AllStudent();
System.out.println("size of s arraylist"+s.size());
for(int i=0;i<s.size();i++)
{
String Ids=s.get(i).getId();
String names=s.get(i).getName();
String passwords=s.get(i).getPass();
String cells=s.get(i).getCell();
String adresss=s.get(i).getAdress();
Object[] data={Ids,names,passwords,cells,adresss};
tablemodel.addRow(data);
}
}
});
Admin_AllStudents_pnl.add(All_Students);
gui.add(Admin_AllStudents_pnl);
only the for loop is not working whole code works fine without for loop every variable is already declared the code is about of 1000 lines so i cant upload all of it.
Related
I am making a simple sudoku and when I want to start a new game, I reload the panel. I first remove it and then add it to the frame. The problem is that I can choose the difficulty for new game, but it always selects the first "Easy" dificulty, not selected. So if I change it in JComboBox to "medium", when page is reloaded it will load the game with "Easy", not "medium".
What should I do so my refreshed panel will accept changed difficulty?
Here are methods that are used for this in my program:
JComboBox difficulty = new JComboBox();
DefaultComboBoxModel difficultyModel = new DefaultComboBoxModel();
difficultyModel.addElement("Easy");
difficultyModel.addElement("Medium");
difficultyModel.addElement("Hard");
difficulty.setModel(tezavnostModel);
difficulty.setSelectedIndex(0);
difficulty.setPreferredSize(new Dimension(100, 25));
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.reloadSudokuBoard();
sudokuBoard.pickDifficulty(getDifficulty()));
}
});
public String getDifficulty() {
return (String)difficulty.getSelectedItem();
}
public void board(int[][] numbers, int zeros) {
int numberZeros = setDifficulty(sudokuForm.getDifficulty());
int[][] boardNumbers = gameNumbers();
public void reloadSudokuBoard() {
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
}
Hope this helps.
public void reloadSudokuBoard() {
int index = difficulty.getSelectedIndex();
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
difficulty.setSelectedIndex(index);
}
Before removing components, you can use the getSelectedIndex to get the index that was selected. After the element have been added, the setSelectedIndex will fix it
I am writing a program where I need to open a JFrame if a button is clicked. I set the default close operation to Dispose_on_close so that when I close the window the program doesn't shutdown completely.
In the frame that will be opened, i want to put a JTable, so I wrote two methods, a createFrame() method and a mechanicListTableProperties() which is the method that creates the JTable and adds elements to it. I then call the mechanicListTableProperties inside the createFrame() and the createFrame inside the actionPerformed() method. When I open the frame 1 time, the table is shown inside the window, but if I close and reopen the frame, the table is also readded and I see 2 tables, when I am trying to just see the one table again. Here is my source code:
public class SeeMechanicsButtonHandler implements ActionListener {
JFrame mechanicListFrame;
boolean isOpen = false;
JTable mechanicListTable;
JPanel tablePanel = new JPanel(new GridLayout());
JScrollPane sp;
List<String> names = new ArrayList<String>();
String[] namesArray;
public void createFrame() {
mechanicListFrame = new JFrame();
mechanicListFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
mechanicListFrame.setSize(new Dimension(500,500));
mechanicListFrame.add(tablePanel);
mechanicListFrame.setVisible(true);
//Prevents the window from being opened multiple times
mechanicListFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
isOpen = false;
}
});
}
public void mechanicListTableProperties(){
mechanicListTable = new JTable(){
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Nome", namesArray);
//Creates a column with title as Nome and lines as the array
mechanicListTable.setModel(model); //adds column to the the table
mechanicListTable.setBounds(30, 40, 200, 300); //table size
mechanicListTable.setFont(new Font("Arial Rounded MT", Font.BOLD, 15));
// adding it to JScrollPane
sp = new JScrollPane(mechanicListTable);
tablePanel.add(sp);
}
public void actionPerformed(ActionEvent e) {
if(!isOpen) {
try {
//SQL code to get the data from mechanics table
ResultSet rs = ServerConnection.createQueryStatement("SELECT * FROM mechanics");
while (rs.next()){
//loop to add each entry in the table to an array list
names.add(rs.getString("nome"));
}
//creates an array to put the values from the arraylist
namesArray = new String[names.size()];
for (int iterate = 0; iterate < names.size(); iterate++){
//loop that iterates through the arraylist and puts the values in the array
namesArray[iterate] = names.get(iterate);
System.out.println(namesArray[iterate]);
//prints to the console for testing purposes
}
} catch (SQLException e1) {
e1.printStackTrace();
}
createFrame();
isOpen = true;
}
}
}
Hi i have a class where i am using mouseclick event i want to call another class when i click from my mouse
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
// System.out.println("Double-clicked on: " + o.toString());
String a=o.toString();
LiistSelection.setListIndex(a);
System.out.println(LiistSelection.getListIndex());
new MyGui4();
}
}
}
};
i want to call this class when user click on list then new window should open
here is my class mygui4.java
public class MyGui4 extends JFrame
{
JLabel jLabel1;
Container pane;
private static ResultSet resultSet = null;
public void Gui( )
{
{
getContentPane().setBackground(new java.awt.Color(255,153,51));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
Border border = LineBorder.createGrayLineBorder();
jLabel1 = new JLabel(image);
jLabel1.setBorder(border);
jLabel1.setBackground(Color.red);
c.add(jLabel1);
setLayout(null);
}
public static void main( String[] args )
{
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
}
}
You want to Create a object of another Class and call a function using a object.
class second
{
//.....
public void function()
{
//........
}
public void function(int index)
{
//..........
}
}
second s=new second();
s.function()//calling function
int i=10;
s.function(i)//calling function with parameter
Try This Example :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class m extends JFrame
{
String s="The Value of List is 10";
m()
{
setVisible(true);
pack();
setLayout(null);
JButton b=new JButton("Click to Open another form");
b.setBounds(10,10,200,40);
add(b);
b.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
new s(s);//calling another class contructor
}
});
}
public static void main (String[] args)
{
new m();
}
}
class s extends JFrame
{
s(String s)
{
setVisible(true);
setSize(100,100);
setTitle(s);
}
}
Click The button Another Class and Open The Window
It looks to me like you are tying to invoke the class MyGui4 from the command line when you start the JVM or from another application when you click on the JList, If so then the code needs to be the same in both places.
When invoked from the command line the main() method is invoked which in turn invokes 3 lines of code:
final MyGui4 frame = new MyGui4();
frame.Gui();
frame.setVisible(true);
When you invoke the code when clicking on the JList you invoke 1 line of code:
new MyGui4();
Can you tell me what the difference is?
Of course I still don't understand the point of this code because none of the methods in your MyGui4 class accept a parameter. So it doesn't matter which item in the JList you click on you will still display the same GUI with the same information. You need to pass the selected object from your JList to your GUI.
I have two Action Listener inner-classes inside one main class. Each one corresponds to its own button. One of the Action Listeners is coded to generate an Array List. The other simply writes that Array List to a Text Field.
My question is how can I refer to/access that data from the other Action Listener? The code below compiles but when I check the contents of the Array List from the second Action Listener, it is empty ([]).
I'm guessing this has something to do with the Array List re-instantiating when the other Action Listener's actionPerformed method is called. How can I work around this? (The code here is just the 2 Action Listeners).
// Create a Button Listener Inner Class for Input Route Button.
class InputRouteButtonHandler implements ActionListener {
List<String> routeStopList = new ArrayList<String>();
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
routeStopList.add(city1); //Add city1 to start of array.
int dialogResult;
do {
String routeStop = JOptionPane.showInputDialog("Enter a stop between the 2 cities:");
routeStopList.add(routeStop);
dialogResult = JOptionPane.showConfirmDialog(null, "Add another stop?");
} while (dialogResult.equals(JOptionPane.YES_OPTION));
routeStopList.add(city2); //Add city2 to end of array.
System.out.println(routeStopList); //Just checking ArrayList contents
}
}
}
// Create a Button Listener Inner Class for Route Button.
class RouteButtonHandler extends InputRouteButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
System.out.println(routeStopList); //Just checking ArrayList contents
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
for (int i = 0; i < routeStopList.size(); i++) {
String addedRoute = routeStopList.get(i);
adminPanelTextArea.append(addedRoute + "\n");
}
}
}
}
You are right, your problem is due to your creating two ArrayLists, lists that have absolulely no relationship with each other, other than holding the same type of objects and having the same names. A solution is to create one Model class that is shared by both ActionListener classes, and in this model class, have your ArrayList. Then give your ArrayList classes a setModel(Model model) method or constructor, and pass in a reference to the single Model object into both ActionListeners.
One other consideration is to use a single Control class to handle your listener type code, and then have your Control class hold a Model field.
As an aside, this is dangerous code:
if (city1 == city2) {
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
For example, say you have two buttons that want to manipulate a JList, one wanting to add text, the other wanting to clear it, then you could pass the JList's model into both button handlers. An example program could look like:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ShareList extends JPanel {
private static final String PROTOTYPE_CELL_VALUE = "ABCDEFGHIJKLMNOP";
private static final int VISIBLE_ROW_COUNT = 10;
private JTextField textField = new JTextField(10);
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> myList = new JList<>(listModel);
public ShareList() {
myList.setPrototypeCellValue(PROTOTYPE_CELL_VALUE);
myList.setVisibleRowCount(VISIBLE_ROW_COUNT);
myList.setFocusable(false);
JPanel buttonPanel = new JPanel();
AddHandler addHandler = new AddHandler(listModel, this);
textField.addActionListener(addHandler);
buttonPanel.add(new JButton(addHandler));
buttonPanel.add(new JButton(new ClearHandler(listModel)));
JPanel rightPanel = new JPanel(new BorderLayout());
rightPanel.add(textField, BorderLayout.NORTH);
rightPanel.add(buttonPanel, BorderLayout.CENTER);
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(new JScrollPane(myList));
add(rightPanel);
}
public String getText() {
textField.selectAll();
return textField.getText();
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ShareList");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShareList());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class AddHandler extends AbstractAction {
private DefaultListModel<String> listModel;
private ShareList shareList;
public AddHandler(DefaultListModel<String> listModel, ShareList shareList) {
super("Add");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
this.listModel = listModel;
this.shareList = shareList;
}
public void actionPerformed(ActionEvent e) {
String text = shareList.getText();
listModel.addElement(text);
};
}
#SuppressWarnings("serial")
class ClearHandler extends AbstractAction {
private DefaultListModel<String> listModel;
public ClearHandler(DefaultListModel<String> listModel) {
super("Clear");
putValue(MNEMONIC_KEY, KeyEvent.VK_C);
this.listModel = listModel;
}
public void actionPerformed(ActionEvent e) {
listModel.clear();
};
}
Newbie here.
When I added an element in the DefaultListModel, I used a class with an overriden toString.
Based on the sample code below, I want to display the selected item's ID when I click the button btnid.
The commands under displayID doesn't seem to work. Help please. Thanks!
class SomeClass {
JFrame f = new JFrame("Sample");
JScrollPane sp = new JScrollPane();
DefaultListModel dlm = new DefaultListModel();
JList lst = new JList(dlm);
public SomeClass() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnadd = new JButton("Add");
JButton btnid = new JButton("View ID");
Container p = f.getContentPane();
sp.getViewport().add(lst,null);
p.add(sp, BorderLayout.WEST);
p.add(btnadd, BorderLayout.EAST);
p.add(btnid, BorderLayout.SOUTH);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlm.addElement(new ElementDisplay(dlm.getSize(),"Element " + dlm.getSize()));
}
});
btnid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayID();
}
});
f.pack();
f.setVisible(true);
}
private void displayID() {
ElementDisplay ed;
ed = dlm.getElementAt(lst.getSelectedIndex());
System.out.println(ed.elementID);
}
public static void main(String args[]) {
SomeClass sc = new SomeClass();
}
class ElementDisplay {
public int elementID;
private String elementDescription;
public ElementDisplay(int pid, String pdesc) {
elementID=pid;
elementDescription=pdesc;
}
#Override
public String toString() {
return elementDescription;
}
}
}
Works fine for me. What makes you think it doesn't work? You need to actually have an item selected in the list for the button press to work, you will get ArrayIndexOutOfBoundException
Instead of depending on a button press, just add a listener to the JList. That way only when the item in the JList is selected, does it print. No need for the button and trying to avoid the ArrayIndexOutOfBoundException
lst.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
JList list = (JList)e.getSource();
DefaultListModel model = (DefaultListModel)list.getModel();
ElementDisplay ed = (ElementDisplay) model.getElementAt(lst.getSelectedIndex());
System.out.println(ed.elementID);
}
}
});
See How to Write Event Listeners where you will run into possible listeners you can use for different components. As GUIs are event driven, you should take time to learn most of them.