I am trying to write a clipboard program that can copy/paste and save to a txt file.
While the program works, I am trying to change the buttons into a Menu with MenuItems,
however, I cannot figure out how to use the Menu item properly, as I cannot add it to a panel.
Please notice I am using AWT and not Swing, so no JPanel/JFrame, etc.
Any tip/help is appreciated.
This is my code and attempt at changing it into a menu, please let me know what I am doing wrong:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CheesyWP extends Frame implements ActionListener {
/**
* #param args
*/
//new panel for menu
Panel north;
//original
Panel center;
Panel south;
Button save;
Button load;
Button clip;
Button finish;
Menu mn;
MenuItem mSave;
MenuItem mLoad;
MenuItem mClip;
MenuItem mFinish;
TextArea ta;
public static void main(String[] args) {
// TODO Auto-generated method stub
CheesyWP cwp = new CheesyWP();
cwp.doIt();
}
public void doIt() {
center = new Panel();
south = new Panel();
clip = new Button("Open Clipboard");
save = new Button("Save");
load = new Button("Load");
finish = new Button("Finish");
//menu items
north = new Panel();
mn = new Menu();
mSave = new MenuItem("Save");
mLoad = new MenuItem("Load");
mClip = new MenuItem("Open Clipboard");
mFinish = new MenuItem("Finish");
mn.add(mSave);
mn.add(mLoad);
mn.add(mClip);
mn.add(mFinish);
mSave.addActionListener(this);
mLoad.addActionListener(this);
mClip.addActionListener(this);
mFinish.addActionListener(this);
//north.add(mn); <-------//PROBLEM HERE
clip.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
finish.addActionListener(this);
ta = new TextArea(20, 80);
center.add(ta);
south.add(load);
south.add(save);
south.add(clip);
south.add(finish);
this.add(center, BorderLayout.CENTER);
this.add(south, BorderLayout.SOUTH);
this.setSize(600, 300);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == save) {
try {
File junk = new File("junk.txt");
FileWriter fw = new FileWriter(junk);
fw.write(ta.getText()); // write whole TextArea contents
fw.close();
} catch (IOException ioe) {
}
}// ends if
if (ae.getSource() == load) {
String temp = "";
try {
File junk = new File("junk.txt");
FileReader fr = new FileReader(junk);
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
ta.append(temp + "\n");
}
br.close();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
if (ae.getSource() == finish) {
System.exit(0);
}
if(ae.getSource()==clip){
new ClipBoard();
}
}
class ClipBoard extends Frame {
public ClipBoard() { // a constructor
this.setTitle("Clipboard");
this.setLayout(new FlowLayout());
this.add(new TextArea(10, 50));
this.setSize(400, 160);
this.setVisible(true);
}
}
}
I hope this code help you:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JMenuTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JMenuTest() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu connectionMenu = new JMenu("Connection");
menuBar.add(connectionMenu);
JMenuItem menuItemConnect = new JMenuItem("Connect");
menuItemConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Connected");
}
});
connectionMenu.add(menuItemConnect);
JMenuItem menuItemDisconnect = new JMenuItem("Disconnect");
menuItemDisconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Disconnected");
}
});
connectionMenu.add(menuItemDisconnect);
JMenuItem menuItemExit = new JMenuItem("Exit");
menuItemExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
connectionMenu.add(menuItemExit);
JMenu mnNewMenu_1 = new JMenu("New menu");
menuBar.add(mnNewMenu_1);
this.setVisible(true);
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* #param args
*/
public static void main(String[] args) {
new JMenuTest();
}
}
Related
I'm having some problems with my class that I need some help with. The class is supposed to take retrieve a csv.file from the file chooser, and then put the name of the file into a Jlist, but I can't get the JList to print the arraylist that I put the chosen files into. This is the code I've got, so I'd be grateful if you could take a look at it and tell me what I need to change with it in order to get the JList to print the arraylist.
import dao.UserDAO;
import db.DemoDB;
import model.Activity;
import model.DataPoint;
import model.Statistics;
public class LoginGUI1 {
DemoDB DemoDBSingleton = null;
private JTabbedPane tabbedPane = new JTabbedPane();
UserDAO userDao = new UserDAO();
JFrame mainFrame = new JFrame("Välkommen till din app");
JFrame f = new JFrame("User Login");
JLabel l = new JLabel("Användarnamn:");
JLabel l1 = new JLabel("Lösenord:");
JTextField textfieldUsername = new JTextField(10);
JPasswordField textfieldPassword = new JPasswordField(10);
JButton loginButton = new JButton("Logga In");
JFileChooser fc = new JFileChooser();
JMenuBar mb = new JMenuBar();
JList listAct = new JList();
List<Activity> activityList = new ArrayList<Activity>();
List activityList1 = new Vector();
JFrame jf;
JMenu menu;
JMenuItem importMenu, exitMenu;
Activity activity = new Activity();
public LoginGUI1() throws IOException {
DemoDBSingleton = DemoDB.getInstance();
ProgramMainFrame();
}
private void ProgramMainFrame() throws IOException {
mainFrame.setSize(800, 600);
mainFrame.setVisible(true);
mainFrame.setJMenuBar(mb);
mainFrame.getContentPane().setLayout(new BorderLayout());;
tabbedPane.add("Dina Aktiviteter", createViewActPanel());
mainFrame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
tabbedPane.add("Diagram för vald aktivitet", createViewDiagramPanel());
tabbedPane.add("Statistik för vald aktivitet", createViewStatisticsPanel());
tabbedPane.add("Kartbild över vald aktivitet", createViewMapPanel());
JMenuBar mb = new JMenuBar();
menu = new JMenu("Meny");
importMenu = new JMenuItem("Importera aktivitet");
importMenu.addActionListener(importActionListener);
exitMenu = new JMenuItem("Avsluta program");
exitMenu.addActionListener(exitActionListener);
menu.add(importMenu);
menu.add(exitMenu);
mb.add(menu);
mainFrame.setJMenuBar(mb);
/* JPanel listholder = new JPanel();
listholder.setBorder(BorderFactory.createTitledBorder("ListPanel"));
mainFrame.add(listholder);
listholder.setVisible(true);
listholder.setSize(500,400);*/
}
private JPanel createViewActPanel() {
JPanel analogM = new JPanel();
analogM.setBackground(new Color(224, 255, 255));
return analogM;
}
ActionListener importActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int returnValue = fc.showOpenDialog(mainFrame);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file != null)
{
String fileName = file.getAbsolutePath();
Activity activity = null;
try {
activity = new Activity();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
activity.csvFileReader(fileName);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
activityList.add(activity);
listAct.setListData(activityList.toArray());
}
}
}
};
public static void main(String[] args) throws IOException {
new LoginGUI();
}
}
There's a lot of context missing, so the best I can do is provide a simple running example which works.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test {
public static void main(String args[]) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList<File> fileList;
private DefaultListModel<File> fileListModel;
public TestPane() {
fileListModel = new DefaultListModel<>();
fileList = new JList(fileListModel);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
fileListModel.addElement(file);
}
}
});
setLayout(new BorderLayout());
add(new JScrollPane(fileList));
add(addButton, BorderLayout.SOUTH);
}
}
}
I'd highly recommend having a look at How to use lists to get a better understanding of how the API works
In the createWorkPanel() method I created a Label and put a picture there, but the picture is not displayed on the screen. Maybe someone knows why, please tell me?
Here is my code:
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class MainWindow extends JFrame {
private JButton button1;
public MainWindow() throws IOException
{
setLayout(new BorderLayout());
createWorkPanel();
setTitle("Графический дизайнер");
//setDefaultLookAndFeelDecorated(true);
setSize(1000,600);
// setLocation(400,100);
// setVisible(true);
// pack(); // automatically size the window to fit its components
setLocationRelativeTo(null); // center this window on the screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void createWorkPanel() throws IOException
{
setLayout(new FlowLayout());
button1 = new JButton("Load Images");
button1.setActionCommand("Button 1 was prassed!");
add(button1);
ActionListener actionListener = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File fImg = MyFileChooser.chooseFile("Image Files (png & jpg)", "png", "jpg");
if (fImg != null)
{
JLabel background=new JLabel(new ImageIcon(fImg.getAbsolutePath()));
// background.setLayout(new FlowLayout());
add(background);
System.out.println(" файл создан");
}
}
};
button1.addActionListener(actionListener);
}
public static void main (String [] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new MainWindow ().setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
class MyFileChooser {
public static File chooseFile(String description, String... extensions) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + selectedFile.getAbsolutePath());
return selectedFile;
} else {
return null;
}
}
}
Follow the below code.
if (fImg != null) {
JLabel background = new JLabel(new ImageIcon(fImg.getAbsolutePath()));
add(background);
MainWindow.this.revalidate();
}
Adding MainWindow.this.revalidate(); should help.
Sorry if its an obvious question.I have been trying to switch panels in the same window using cardlayout.But when i run my application nothing happens.
System.out.println(mntmBookingStatus);
the above statement does get printed on console.but not able to make out why cards arent switching when i click on menuitem "booking status" and "invoice entry".
public class StartDemo {
private JFrame frame;
private JPanel cards = new JPanel(new CardLayout());
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StartDemo window = new StartDemo();
window.initialize();
window.frame.pack();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 772, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
// main menu
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
// mainmenuoption-1
mnNewMenu = new JMenu("Entries");
menuBar.add(mnNewMenu);
// option-1 items
mntmBookingStatus = new JMenuItem("Booking Status");
mnNewMenu.add(mntmBookingStatus);
mntmBookingStatus.addActionListener(new MenuListenerAdapter());
mntmInvoiceEntry = new JMenuItem("Invoice Entry");
mnNewMenu.add(mntmInvoiceEntry);
mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());
StartDemo demo = new StartDemo();
demo.addComponentToPane(frame.getContentPane());
}
public void addComponentToPane(Container pane) {
JPanel booking_status = new JPanel();
JPanel invoice_entry = new JPanel();
JPanel customer_ledger = new JPanel();
JPanel create_user = new JPanel();
try {
JPanelWithBackground panelWithBackground = new JPanelWithBackground(
"D:\\Kepler Workspace\\WEDemo\\images\\abc.jpg");
cards.add(panelWithBackground, "name_282751308799");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the layout code for all the panels is written here.
//its to big to post here
cards.add(booking_status, BOOKINGPANEL);
cards.add(invoice_entry, INVOICEPANEL);
cards.add(customer_ledger, CUSTOMERLEDGER);
cards.add(create_user, CREATEUSER);
pane.add(cards, BorderLayout.CENTER);
}
public class MenuListenerAdapter implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout c = (CardLayout) (cards.getLayout());
if (e.getSource() == mntmBookingStatus) {
c.show(cards, BOOKINGPANEL);
System.out.println(mntmBookingStatus);
} else if (e.getSource() == mntmInvoiceEntry) {
c.show(cards, INVOICEPANEL);
System.out.println(mntmInvoiceEntry);
}
}
This is my JPanelWithBackground class
public class JPanelWithBackground extends JPanel {
private Image backgroungImage;
private Image scaledBackgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroungImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
// Draw the backgroung image
g.drawImage(backgroungImage, 0, 0,getWidth(),getHeight(),null);
}
It's these two lines right here
StartDemo demo = new StartDemo();
demo.addComponentToPane(frame.getContentPane());
Since your initialize() method isn't static I think it's safe to assume that you instantiate youe StartDemo again in the main method. In that case, the above code truly is your problem and would totally explain why it doesn't work. Just do this
//StartDemo demo = new StartDemo(); <-- get rid of this.
addComponentToPane(frame.getContentPane());
Tested with code additions only to get it running. Also please not my comments above. setVisible(true) generally is the last thing you should do after adding all components.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartDemo {
private JFrame frame;
private JPanel cards = new JPanel(new CardLayout());
JMenuBar menuBar;
JMenu mnNewMenu;
JMenuItem mntmBookingStatus;
JMenuItem mntmInvoiceEntry;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new StartDemo().initialize();
}
});
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 772, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// main menu
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
// mainmenuoption-1
mnNewMenu = new JMenu("Entries");
menuBar.add(mnNewMenu);
// option-1 items
mntmBookingStatus = new JMenuItem("Booking Status");
mnNewMenu.add(mntmBookingStatus);
mntmBookingStatus.addActionListener(new MenuListenerAdapter());
//StartDemo demo = new StartDemo();
addComponentToPane(frame.getContentPane()); mntmInvoiceEntry = new JMenuItem("Invoice Entry");
mnNewMenu.add(mntmInvoiceEntry);
mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());
frame.setVisible(true);
}
public void addComponentToPane(Container pane) {
JPanel booking_status = new JPanel();
JPanel invoice_entry = new JPanel();
//JPanel customer_ledger = new JPanel();
//JPanel create_user = new JPanel();
try {
JPanelWithBackground panelWithBackground = new JPanelWithBackground(
"/resources/stackoverflow5.png");
cards.add(panelWithBackground, "name_282751308799");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cards.add(booking_status, "booking");
cards.add(invoice_entry, "invoice");
//cards.add(customer_ledger, CUSTOMERLEDGER);
//cards.add(create_user, CREATEUSER);
pane.add(cards, BorderLayout.CENTER);
}
class JPanelWithBackground extends JPanel {
Image img;
public JPanelWithBackground(String path) throws IOException {
img = ImageIO.read(getClass().getResource(path));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
public class MenuListenerAdapter implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout c = (CardLayout) (cards.getLayout());
if (e.getSource() == mntmBookingStatus) {
c.show(cards,"booking");
System.out.println(mntmBookingStatus);
} else if (e.getSource() == mntmInvoiceEntry) {
c.show(cards, "invoice");
System.out.println(mntmInvoiceEntry);
}
}
}
}
I have a JInternalframe (tab_items) inside a desktop pane. I want to open another JInternalframe (frm_add_items) within the same desktop pane, whenever user clicks the popup menu in tab_items. How can I do this?
//class tab_items
public class tab_items extends JInternalFrame implements MouseListener,DocumentListener,ActionListener{
DS co= new DS ();
JPanel panel1;
JScrollPane pane;
DefaultTableModel model= new DefaultTableModel();
JTable tbl= new JTable(model);
JLabel lbl_search;
JTextField txt_search;
JPopupMenu pop;
JMenuItem mi_add,mi_edit, mi_del;
public tab_items(){
panel1= new JPanel();
panel1.setLayout(null);
//popupmenu
pop=new JPopupMenu();
mi_add=new JMenuItem("Add new record");
mi_edit=new JMenuItem("Edit record");
mi_del=new JMenuItem("Delete record");
add(pop);
pop.add(mi_add);
mi_add.addActionListener(this);
mi_add.addMouseListener(this);
pop.add(mi_edit);
mi_edit.addActionListener(this);
pop.add(mi_del);
mi_del.addActionListener(this);
// try{
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// }catch(Exception ex){}
initcomponents();
setVisible(true);
setSize(700,500);
setLocation(100,150);
setTitle("List Of Items");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void initcomponents(){
try{
model.addColumn("ID");
model.addColumn("Item Name");
model.addColumn("Cost Price");
model.addColumn("Selling Price");
model.addColumn("Qty");
tbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
PreparedStatement pstat=co.con.prepareStatement("Select * from tbl_items ORDER BY itemid ASC");
ResultSet rs=pstat.executeQuery();
while(rs.next()){
model.addRow(new Object[]{rs.getInt(1), rs.getString(2).trim(), rs.getString(3).trim(), rs.getString(4).trim(),rs.getInt(5)});
}
}catch(Exception ex){}
// SETTING COLUMN WIDTH
TableColumnModel model=tbl.getColumnModel();
model.getColumn(0).setPreferredWidth(50);
model.getColumn(1).setPreferredWidth(400);
model.getColumn(2).setPreferredWidth(100);
model.getColumn(3).setPreferredWidth(100);
model.getColumn(4).setPreferredWidth(50);
// adding panel
add(panel1);
panel1.setBounds(0,0,800,600);
//scrollpane initialize
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
pane=new JScrollPane(tbl, v, h); //table included in scrollpane
panel1.add(pane);
pane.setBounds(0,50,700,400);
tbl.addMouseListener(this);
lbl_search= new JLabel();
lbl_search.setIcon(new ImageIcon(getClass().getResource("/img/btn_search_up.png")));
panel1.add(lbl_search);
lbl_search.setBounds(5,10,25,20);
txt_search=new JTextField();
panel1.add(txt_search);
txt_search.setBounds(35,10,200,20);
txt_search.getDocument().addDocumentListener(this);
/*
btn_add= new JButton();
btn_add.setIcon(new ImageIcon(getClass().getResource("/img/add-button-md.png")));
// btn_add.setHorizontalAlignment(SwingConstants.CENTER);
// btn_add.setText("Add");
add(btn_add);
btn_add.setBounds(665, 125, 65, 65);
btn_edit= new JButton();
btn_edit.setText("Update");
add(btn_edit);
btn_edit.setBounds(665, 200, 65, 65);
btn_delete=new JButton();
btn_delete.setText("Delete");
add(btn_delete);
btn_delete.setBounds(665, 275, 65, 65);
*/
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent me){maybeShowPopup(me);}
public void mouseReleased(MouseEvent me){maybeShowPopup(me);}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private void maybeShowPopup(MouseEvent e){
if (e.isPopupTrigger()){
pop.show(e.getComponent(),e.getX(), e.getY());
}
}
public void update(DocumentEvent de){
Document doc=(Document)de.getDocument();
int length=doc.getLength();
String str=null;
try
{
str=doc.getText(0,length);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error in retreiving Search Length\n"+ex);
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dstore","root","");
PreparedStatement pstat=con.prepareStatement("select * from tbl_items where itemid LIKe '"+str+"%' OR itemname LIKe '"+str+"%' ORDER BY itemid ASC");
ResultSet rs=pstat.executeQuery();
model.setRowCount(0);
while(rs.next()){
model.addRow(new Object[]{rs.getInt(1), rs.getString(2).trim(), rs.getString(3).trim(), rs.getString(4).trim(),rs.getInt(5)});
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"ERROR IN DOCUMENT LISTENER.\nCannot Fetch Records"+ex);
}
}
public void insertUpdate(DocumentEvent de) {
update(de);
}
public void removeUpdate(DocumentEvent de) {
update(de);
}
public void changedUpdate(DocumentEvent de) {
update(de);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==mi_add){
// frm_add_item ob= new frm_add_item();
// ob.show();
// dp.add(ob);
}else if(ae.getSource()==mi_edit) {
}else {
}
}
}
#//class frm_main ( it contains desktop pane)#
Several issues raised by your fragment bear closer scrutiny:
Use Action to encapsulate functionality.
Don't extend JInternalFrame needlessly; use a factory method.
Don't use setBounds(); use a layout manager.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyVetoException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
//** #see http://stackoverflow.com/a/18556224/230513 */
public class Test {
private JDesktopPane jdp = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
};
private NewAction newAction = new NewAction("New");
public Test() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newAction.actionPerformed(null);
frame.add(jdp);
frame.pack();
frame.setVisible(true);
}
private void createInternalFrame(int x, int y) {
final JInternalFrame jif =
new JInternalFrame("Test" + x, true, true, true, true);
jif.setLocation(x, y);
JPanel jp = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(256, 128);
}
};
JPopupMenu popup = new JPopupMenu();
jp.setComponentPopupMenu(popup);
popup.add(new JMenuItem(newAction));
jp.add(new JButton(newAction));
jif.add(jp);
jif.pack();
jdp.add(jif);
jif.setVisible(true);
try {
jif.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace(System.err);
}
}
private class NewAction extends AbstractAction {
private int i;
public NewAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent ae) {
i++;
createInternalFrame(50 * i, 50 * i);
}
}
}
You have to add later JInternalFrame in parent of first JInternalFrame. For example you add first JInternalFrame in JDesktopPane as
JdesktopPane.add(JInternalFrame_obj1);
JInternalFrame_obj1.toFront();
Then click on a button to add another JInternalFrame. If button is placed on other than shown JInternalFrame
JdesktopPane.add(JInternalFrame_obj2);
JInternalFrame_obj2.toFront();
If button is placed on JInternalFrame_obj1 add
this.getParent().add(JInternalFrame_obj12);
JInternalFrame_obj2.toFront();
I have a JPanel with a JLabel in it, is it possible to have a mouse click on JLabel, following by another mouse click on any location on the JPanel to create an instance of the JLabel. Basically, I can click the JLabel and create new instances of it anywhere on the JPanel.
Here is a simple example of what you are looking for. What you need is deepCopy of the clicked JLabel and then retrieve it back and draw it to the JPanel.
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.border.*;
class CopyLabel extends JFrame
{
JPanel panel ;
JPanel centerPanel;
int clickCount = 0;
ByteArrayOutputStream baos;
ByteArrayInputStream bins;
public void createAndShowGUI()
{
setTitle("Copy JLabel");
JLabel label1 = new JLabel("JLabel1");
JLabel label2 = new JLabel("JLabel2");
panel = new JPanel();
label1.setForeground(Color.blue);
label2.setForeground(Color.red);
panel.add(label1);
panel.add(label2);
class MyMouseAdapter extends MouseAdapter
{
#Override
public void mouseClicked(MouseEvent evt)
{
clickCount = 1;
try
{
deepCopy((JLabel)evt.getSource());
}
catch (Exception ex){}
}
}
label1.addMouseListener(new MyMouseAdapter());
label2.addMouseListener(new MyMouseAdapter());
panel.setBorder(BorderFactory.createTitledBorder("Controllers"));
getContentPane().add(panel,BorderLayout.SOUTH);
centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(),"Drawing Pad",TitledBorder.CENTER,TitledBorder.TOP));
centerPanel.setLayout(null);
centerPanel.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent evt)
{
if (clickCount == 1)
{
try
{
pasteLabel(evt.getX(),evt.getY());
}
catch (Exception ex){}
}
}
});
getContentPane().add(centerPanel);
setSize(300,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void deepCopy(JLabel label)throws Exception
{
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(label);
oos.close();
}
public void pasteLabel(int x, int y)throws Exception
{
if (clickCount == 1)
{
bins = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream oins = new ObjectInputStream(bins);
JLabel obj = (JLabel)oins.readObject();
centerPanel.add(obj);
obj.setBounds(x,y,obj.getWidth(),obj.getHeight());
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
CopyLabel cl = new CopyLabel();
cl.createAndShowGUI();
}
});
}
}
You can attach mouse listener to your JLabel like this
final JLabel jlabel = new JLabel("Test");
jlabel.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Hello : "+ e);
Point location = MouseInfo.getPointerInfo().getLocation();
targetPanel.add(cloneLabelAt(jlabel, location));
}
});
private JLabel cloneLabelAt(JLabel label, Point location)
{
JLabel cloned = new JLabel(label.getText());
cloned.setLocation(location);
return cloned;
}
Inside your mouse click handler you can create another JLabel and add it to your target panel