#5, First Floor, 4th Street , Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to use JMenu in java?

Description

This program demonstartes how to use JMenu in GUI. JMenuBar object is added to JFrame and then JMenuIem object is added to JMenu. Action performed method for JMenu Item is written in which data from the database is selected and dispalyed.

Sample Code
  • Filename: JMenuTest.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import javax.swing.table.*;
class JMenuTest {
JLabel label1;
JPanel panel;
JButton button1;
JButton button2;
JButton button3;
JFrame jf;
JMenuBar jMenuBar;
JMenu jMenu1,jMenu2,jMenu3;
JMenuItem jMenuItem1,jMenuItem2,jMenuItem3,jMenuItem4,jMenuItem5;

JMenuTest () {
jf=new javax.swing.JFrame("Result");
panel=new javax.swing.JPanel();
jf.add(panel);
panel.setLayout(null);
jf.setSize(700,500);
jf.show();

Image uimage1 = Toolkit.getDefaultToolkit().getImage("images/rs.jpg");
ImageIcon icon1 = new ImageIcon(uimage1);

label1 = new JLabel(icon1);
label1.setBounds(250,10,235,170);

panel.add(label1);

jMenuBar = new javax.swing.JMenuBar();

jMenu1 = new javax.swing.JMenu();
jMenu1.setText("Student");
jMenuBar.add(jMenu1);

jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem1.setText("View Student Marks");
jMenu1.add(jMenuItem1);

jf.setJMenuBar(jMenuBar);

handlingEvents();

}

public void handlingEvents() {

jMenuItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
displayTable("Student_Marks",200);
}
});
}

void displayTable(String table,int y) {
Vector columnNames2 = new Vector();
Vector data2 = new Vector();
String nam2 = table;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con2 = DriverManager.getConnection("jdbc:odbc:user");
String sql2 = "Select * from "+nam2+"";
Statement stmt2 = con2.createStatement();
ResultSet rs2 = stmt2.executeQuery( sql2 );
ResultSetMetaData md2 = rs2.getMetaData();
int columns2 = md2.getColumnCount();
for (int i = 1; i <= columns2; i++) {
columnNames2.addElement( md2.getColumnName(i) );
}
while (rs2.next()) {
Vector row2 = new Vector(columns2);
for (int i = 1; i <= columns2; i++)
{
row2.addElement( rs2.getObject(i) );
}
data2.addElement( row2 );
}
rs2.close();
stmt2.close();

final JTable table2 = new JTable(data2, columnNames2);
JTableHeader header = table2.getTableHeader();
header.setBackground(Color.yellow);

JScrollPane scrollPane = new JScrollPane( table2 );
panel.add( scrollPane );
scrollPane.setBounds(60,y,550,100);
table2.setFont(new Font("Dialog", Font.BOLD, 12));
}
catch(Exception e)
{
System.out.println(e);
}
}

public static void main(String args[]) {
JMenuTest menutest = new JMenuTest();
}
}


Screenshots