How to open another JInternalframe from JInternalframe within the same desktop pane - java

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();

Related

JLabel moves with text entered into JTextArea

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.

Not able to switch cards in cardlayout in single jframe

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);
}
}
}
}

How to select text fields using tab key in java

When I press tab key on the keyboard I want to select my text fields in above order.how to do that?
Try this example....
package com.Demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class TabTest extends JFrame {
public TabTest() {
initialize();
}
private void initialize() {
setSize(300, 300);
setTitle("JTextArea TAB DEMO");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextField textField = new JTextField();
JPasswordField passwordField = new JPasswordField();
final JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
//
// Add key listener to change the TAB behaviour in
// JTextArea to transfer focus to other component forward
// or backward.
//
textArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiers() > 0) {
textArea.transferFocusBackward();
} else {
textArea.transferFocus();
}
e.consume();
}
}
});
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(passwordField, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TabTest().setVisible(true);
}
});
}
}
jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);
try this :)
Try this:
txtfld.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfld.setText("aaa");
}
#Override
public void focusLost(FocusEvent e) {
...
}
});
see more complete code.

changing color of the JLABEL with a link

how can i change the color of a JLABEL with a link in java?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class XXX extends JFrame {
XXX(){
final JLabel lab1=new JLabel("Username:");
final JTextField text1=new JTextField(20);
lab1.setBounds(20,140,65,20);
text1.setBounds(85,141,185,20);
add(lab1);
add(text1);
lab1.setForeground(Color.white);
final JLabel lab2=new JLabel("Password:");
final JPasswordField text2=new JPasswordField(20);
lab2.setBounds(20,165,65,20);
text2.setBounds(85,166,185,20);
add(lab2);
add(text2);
lab2.setForeground(Color.white);
final JButton a=new JButton("Sign In");
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Code
}
});
a.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
a.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
a.setEnabled(false);
text1.setEditable(false);
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
a.setBounds(85,192,80,20);
add(a);
final String strURL = "http://www.yahoo.com";
final JLabel lab3 = new JLabel("<html>Register</html>");
lab3.setBounds(170,192,52,20);
add(lab3);
lab3.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
lab3.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
lab3.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
final JLabel map = new JLabel(new ImageIcon(getClass().getResource("XXXBG.png")));
map.setBounds(0,0,300,250);
add(map);
setTitle("XXX");
setSize(300,250);
setResizable(false);
setCursor(DEFAULT_CURSOR);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(8, 8);
setLayout(null);
toFront();
setVisible(true);
}
public static void main(String[] args)
{
new XXX();
}
}
as you can see, i cant change the foreground color of JLABEL lab3.
if posible, i want also to change color of border-like of the jframe.
anyone can help?
Yes, it's possible. Simple supply the foreground color you want to use...
lab3.setForeground(Color.BLUE);
You also don't need the mouse listener. Simply using lab3.setCursor(new Cursor(Cursor.HAND_CURSOR)); will change the mouse cursor automatically when the mouse is moved over the label for you...magically :D
Updated
public class TestLabel01 {
public static void main(String[] args) {
new TestLabel01();
}
public TestLabel01() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JLabel link = new JLabel("Linked in");
link.setForeground(Color.BLUE);
link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(link);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

JButton and JLabel don't show on JDialog and sleep not work

I have a frame that when i click ok button on tester2 frame, tester1 frame should be seen and when click showbumber button, a random number should be displayed in my label.
But i can't see this generated number while i use sleep method!
Thank for help.
public class tester2 extends JFrame implements ActionListener {
public tester2() {
setTitle("Hello");
setLayout(new FlowLayout());
JButton okButton = new JButton("Ok");
okButton.addActionListener(this);
add(okButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
tester1 tester1 = new tester1(tester2.this);
tester1.setVisible(true);
}
public static void main(String[] args) {
new tester2().setVisible(true);
}
}
tester 1:
public class tester1 extends JDialog implements ActionListener {
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel(" ");
this.add(showButton);
this.add(lbl1);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
GenerateNumber();
tester1.this.dispose();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
try {
Thread.sleep(1000);
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
}
}
If your intention is to close the second frame automatically after a short delay, you should use a javax.swing.Timer instead.
Blocking the EDT will stop it from (amongst other things) processing repaint request, which means your UI can't be updated when you can Thread.sleep
Instead you should use a javax.swing.Timer
public void GenerateNumber() {
Random rnd1 = new Random();
try {
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
I don't if your dialog shows the showButton and Label before. Because i have to add a panel in order to show them. After that you need a Timer Class to deal with auto dispose.
Your tester1 look now like this
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class tester1 extends JDialog implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
this.add(jPanel);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel();
jPanel.add(showButton, BorderLayout.NORTH);
jPanel.add(lbl1, BorderLayout.CENTER);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == showButton) {
GenerateNumber();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
lbl1.setText(String.valueOf(rnd1.nextInt(1000000)));
Timer timer = new Timer(1000 * 1, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
}

Categories

Resources