I am creating a swing file editor. I have a JLabel, and a JTextArea in my JFrame. When I type in the JTextArea, I notice the JLabel moving. Here is a Screencastify of this: Screencastify
Is this related to the BoxLayout I am using? Can you please help me explain this behavior, and possibly solve it?
Here is my code:
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileNotFoundException;
public class Editor2 extends JFrame{
private static final long serialVersionUID = 1L;
private static final String appName="JEdit: ";
Container c;
JMenuBar menubar;
JMenu filemenu,edit,optionsmenu;
JMenuItem save,saveas,
newfile,openfile,close,
find,clearfind,
textcolor;
JLabel filetitle;
JTextArea filecontent;
WriteFile out;
ReadFile in;
JFileChooser jfc;
File f;
Document filecontentdoc;
boolean upToDate;
Highlighter h;
DefaultHighlightPainter dhp;
public Editor2() throws FileNotFoundException {
super(appName+"Untitled");
f=null;
upToDate=true;
c=getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS));
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
filetitle = new JLabel("Editing Untitled");
c.add(filetitle);
menubar=new JMenuBar();
setJMenuBar(menubar);
filemenu = new JMenu("File");
edit = new JMenu("Edit");
optionsmenu = new JMenu("Options");
menubar.add(filemenu);
menubar.add(edit);
menubar.add(optionsmenu);
save=new JMenuItem("Save");
saveas=new JMenuItem("Save As");
newfile=new JMenuItem("New File");
openfile=new JMenuItem("Open File");
close=new JMenuItem("Close");
filemenu.add(save);
filemenu.add(saveas);
filemenu.add(newfile);
filemenu.add(openfile);
filemenu.add(close);
find=new JMenuItem("Find");
clearfind=new JMenuItem("Clear Highlights");
edit.add(find);
edit.add(clearfind);
textcolor=new JMenuItem("Text Color");
optionsmenu.add(textcolor);
filecontent = new JTextArea(50,50);
c.add(filecontent);
filecontentdoc=filecontent.getDocument();
filecontentdoc.addDocumentListener(new DocumentListener() {
#Override public void removeUpdate(DocumentEvent e) {}
#Override
public void insertUpdate(DocumentEvent e) {
upToDate=false;
}
#Override public void changedUpdate(DocumentEvent e) {}
});
h = filecontent.getHighlighter();
dhp = new DefaultHighlightPainter(Color.YELLOW);
//pack();
setSize(1000, 1000);
this.addWindowListener(new WindowListener() {
#Override public void windowOpened(WindowEvent e) {}
#Override public void windowIconified(WindowEvent e) {}
#Override public void windowDeiconified(WindowEvent e) {}
#Override public void windowDeactivated(WindowEvent e) {}
#Override public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
#Override public void windowClosed(WindowEvent e) {
dispose();
System.exit(0);
}
#Override public void windowActivated(WindowEvent e) {}
});
}
public static void main(String[] args) throws FileNotFoundException {
Editor2 ef = new Editor2();
ef.setVisible(true);
}
public void setVisible(boolean b){
super.setVisible(b);
}
}
You forgot to place the JTextArea in a JScrollPane. Change this:
c.add(filecontent);
to this:
c.add(new JScrollPane(filecontent));
Also, you probably should use a BorderLayout instead of a BoxLayout, and you should put that JScrollPane in the center of the BorderLayout. Note that a JFrame’s content pane already uses a BorderLayout by default, so you don’t have to change the layout at all, just specify the correct BorderLayout constraints when adding components to it.
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
System.out.println("hi");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size. addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent e) {
inText=size.getText();
pane.revalidate();
pane.repaint();
}
public static void main(String[] args){
new TheSize();
}
}
a couple of things
I made sure the KeyListener is working, and it is not working as in no output, it didn't give me any error.
What should happen:
It should pop a frame which says I would like my grid to be 2^__(user input Textfield)____* 2^(what is in the textfield). (Button for I'm done).
however, (what is in the textfield) remains empty after I type something into the text field. I checked whether the program heard my keystrokes using System.out.println();, and it is working, so the revalidate(); and repaint() commands must not be(I also tested it out by putting a System.out.println(); in my constructor. Thanks in advance
Never use a KeyListener on a JTextField. Get rid of the KeyListener and the JTextField should likely accept text just fine. Instead, if you want to register user input, use a DocumentListener if you just want the text but won't filter it, or a DocumentFilter if you need to filter the text before it is displayed. This sort of question has been asked many times on this site.
Also note that your JLabel will never change, even if you do use a DocumentListener since you call setText(...) on your word1 JLabel but never re-call this method. Just changing the String that the inText String variable refers to of course will not magically change the JLabel's displayed text.
Note, that I'm not sure what you mean by the replicate() command as I've not heard of this method. Do you mean revalidate() if so, please clarify.
For example:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
// Avoid extending JFrames if at all possible.
// and only extend other components if needed.
#SuppressWarnings("serial")
public class TheSize2 extends JPanel {
private static final String FORMAT = "* 2^ %s";
private static final int PREF_W = 550;
private static final int PREF_H = 100;
private String inText = "";
private JLabel word0 = new JLabel("I would like my grid to be 2^", JLabel.RIGHT);
private JLabel word1 = new JLabel(String.format(FORMAT, inText), JLabel.RIGHT);
private JButton finish = new JButton("I'm done");
private JTextField size = new JTextField("", 3);
public TheSize2() {
finish.setAction(new FinishAction("I'm Done"));
size.getDocument().addDocumentListener(new SizeListener());
add(word0);
add(size);
add(word1);
add(finish);
}
#Override // make JPanel bigger
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class SizeListener implements DocumentListener {
private void textUpdated(DocumentEvent e) {
try {
inText = e.getDocument().getText(0, e.getDocument().getLength());
word1.setText(String.format(FORMAT, inText));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
textUpdated(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
textUpdated(e);
}
}
private class FinishAction extends AbstractAction {
public FinishAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
if (comp == null) {
return;
}
Window win = SwingUtilities.getWindowAncestor(comp);
if (win == null) {
return;
}
win.dispose();
}
}
private static void createAndShowGui() {
TheSize2 theSize2 = new TheSize2();
JFrame frame = new JFrame("The Size");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(theSize2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I found the solution with the help of Hovercraft Full Of Eels, all I missed was to re setSize. It is not the best solution, but it is simple enough for me to understand.
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TheSize extends JFrame implements ActionListener, KeyListener {
static String inText="";
JPanel pane=new JPanel();
JLabel word0=new JLabel("I would like my grid to be 2^",JLabel.RIGHT);
JLabel word1=new JLabel("* 2^ "+inText,JLabel.RIGHT);
JButton finish=new JButton("I'm done");
JTextField size=new JTextField("",3);
public TheSize(){
super("size");
setLookAndFeel();
setSize(550,100);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout box=new FlowLayout();
setLayout(box);
pane.add(word0);
pane.add(size);
pane.add(word1);
pane.add(finish);
finish.addActionListener(this);
add(pane);
setVisible(true);
pack();
size.addKeyListener(this);
setFocusable(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args){
new TheSize();
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
inText=size.getText();
word1.setText("* 2^ "+inText);
pane.revalidate();
pane.repaint();
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
I have this code where I designed an editable JComboBox to listen to my keyPressed event and show a message that the key is pressed. But I have no idea why this not working. As a beginner I might have gone wrong logically/conceptually.
So, I would request for suggestions about how to construct the code, so that it works.
Code
import javax.swing.*;
import java.awt.*;
public class testEJCBX extends JFrame {
JComboBox jcbx = new JComboBox();
public testEJCBX() {
super("Editable JComboBox");
jcbx.setEditable(true);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jcbx);
jcbx.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt)
{
jcbxKeyPressed(evt);
}
});
setSize(300, 170);
setVisible(true);
}
private void jcbxKeyPressed(java.awt.event.KeyEvent evt) {
JOptionPane.showMessageDialog(null, "Key Pressed");
}
public static void main(String argv[]) {
new testEJCBX();
}
}
You shouldn't be using a KeyListener for this sort of thing. Rather if you want to detect changes to the combo box's editor component, extract it and add a DocumentListener to it:
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.*;
public class TestEJCBX extends JFrame {
JComboBox<String> jcbx = new JComboBox<>();
public TestEJCBX() {
super("Editable JComboBox");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jcbx.setEditable(true);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jcbx);
JTextField editorComponent = (JTextField) jcbx.getEditor()
.getEditorComponent();
Document doc = editorComponent.getDocument();
doc.addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
System.out.println("text changed");
}
#Override
public void insertUpdate(DocumentEvent e) {
System.out.println("text changed");
}
#Override
public void changedUpdate(DocumentEvent e) {
System.out.println("text changed");
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String argv[]) {
new TestEJCBX();
}
}
I need the frame to update and display how many times the Button has been pressed (the button's text to update)
If I can use actionPreformed() to be locked on to specific events (Button press, or the Menu item being pressed), then I think that should help...
Problems:
When Button is pressed it creates more frames
The existing Frame(s) do not update (I only want there to be one frame anyway)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ButtonFrame implements InternalFrameListener, ActionListener
{
JFrame myFrame = null;
private int clicked;
final String F=("Clicked: "+clicked+" Times!");
public static void main(String[] a)
{
(new ButtonFrame()).test();
}
private void test()
{
myFrame = new JFrame("Internal Frame with a Button");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400,400);
myFrame.setContentPane(new JDesktopPane());
JMenuBar Start_Bar = new JMenuBar();
JMenu Start_Menu = new JMenu("Frame");
JMenuItem Start_Item = new JMenuItem("Start");
Start_Item.addActionListener(this);
Start_Menu.add(Start_Item);
Start_Bar.add(Start_Menu);
myFrame.setJMenuBar(Start_Bar);
myFrame.setVisible(true);
}
public void actionPerformed(ActionEvent Start_Item)
{
JInternalFrame f = new JInternalFrame("Button Frame");
f.setResizable(true);
f.setClosable(false);
f.setMaximizable(true);
f.setIconifiable(true);
f.setSize(200,200);
f.setLocation(100,100);
f.addInternalFrameListener(this);
f.setVisible(true);
Button objButton1;
objButton1=new Button ("Clicked: "+clicked+" Times!");
objButton1.setBounds(20,90,40,50);
f.add(objButton1);
objButton1.addActionListener(this);
myFrame.getContentPane().add(f);
}
public void actionPreformed(ActionEvent objButton1)
{
clicked++;
}
public void internalFrameActivated(InternalFrameEvent e)
{
System.out.println("Internal Button Ready");
}
public void internalFrameClosed(InternalFrameEvent e)
{
System.out.println("Internal frame closed");
}
public void internalFrameClosing(InternalFrameEvent e)
{
System.out.println("Internal frame closing");
}
public void internalFrameDeactivated(InternalFrameEvent e)
{
System.out.println("Internal frame deactivated");
}
public void internalFrameDeiconified(InternalFrameEvent e)
{
System.out.println("Internal frame deiconified");
}
public void internalFrameIconified(InternalFrameEvent e)
{
System.out.println("Internal frame iconified");
}
public void internalFrameOpened(InternalFrameEvent e)
{
System.out.println("Internal frame opened");
}
}
Based on your description, you solution is screaming isolation and separation of code responsibility, the code responsible for managing the button should be separated from the code managing the frame and desktop pane
This way, you can use separate ActionListeners as well as isolate the functionality to a single instance of the button class
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDesktopPane dp = new JDesktopPane();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar Start_Bar = new JMenuBar();
JMenu Start_Menu = new JMenu("Frame");
JMenuItem Start_Item = new JMenuItem("Start");
Start_Item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("Button", true, true, true, true);
f.setSize(200, 200);
f.setLocation(100, 100);
f.add(new ButtonPane());
f.setVisible(true);
dp.add(f);
}
});
Start_Menu.add(Start_Item);
Start_Bar.add(Start_Menu);
frame.setJMenuBar(Start_Bar);
frame.add(dp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonPane extends JPanel {
private JButton button;
private int count = 0;
public ButtonPane() {
setLayout(new GridBagLayout());
button = new JButton("0");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count++;
button.setText(Integer.toString(count));
}
});
add(button);
}
}
}
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'm a java beginner and I tried making a basic program that will delete a certain file in the temp files in Windows. It did delete the file without a problem when I hadn't implemented the JPanel & JFrame but I haven't had any luck since. It is supposed to delete the file when the "Delete for sure" jbutton is pressed and exit the program when the "exit" jbutton is pressed. All it does right now is bring up the GUI and nothing else. Not even system out prints. Here is the code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Andrew
* Date: 12/4/12
* Time: 7:09 PM
* To change this template use File | Settings | File Templates.
*/
public class DeleteFile {
public static void main (String args[]) throws IOException {
frame.setVisible(true);
frame.setName(boxname);
frame.setSize(100, 150);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
button1.setText(buttontext);
button1.setVisible(true);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
deleteFile();
JLabel label = new JLabel("Deletion was successful");
JPanel panel = new JPanel();
panel.add(label);
}
}
class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
public void windowEvent (WindowEvent e) {
System.exit(0);
}
}
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Delete for sure?");
panel.add(button);
button.addActionListener (new Action1());
panel.setName(boxname);
JButton button2 = new JButton("Exit");
panel.add(button2);
button2.addActionListener (new Action2());
// JLabel label = new JLabel(filePath);
// panel.add(label);
}
static String buttontext = "Delete file for sure?";
static String boxname = "Trepix Temp File Deleter";
static String filePath = "C:\\Users\\Andrew\\AppData\\Local\\Temp\\CamRec0\\cursor-1.ico";
static JFrame frame = new JFrame();
static JButton button1 = new JButton();
static JPanel panel = new JPanel();
public static boolean fileIsValid() {
File file = new File(filePath);
if (file.exists()) {
return true;
} else {
return false;
}
}
public static void deleteFile() {
if (fileIsValid() == true) {
File file = new File(filePath);
file.delete();
}
}
}
class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
deleteFile();
JLabel label = new JLabel("Deletion was successful");
JPanel panel = new JPanel();
panel.add(label);
}
}
The panel object is never placed in any container that is part of a hierarchy leading to a top-level window. In other words, it's not placed in anything that is sitting in either a JFrame or JDialog, and so it will never be displayed.
class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
public void windowEvent (WindowEvent e) {
System.exit(0);
}
}
It makes no sense to place this windowEvent method in an ActionListener, since that is part of a WindowListener, something completely different. Why not simply call System.exit(0); in the actionPerformed(...) method?
Also your code shouldn't have any static fields or methods as that is antithetical to object-oriented programming.