Search Results

Search found 39 results on 2 pages for 'gridbaglayout'.

Page 2/2 | < Previous Page | 1 2 

  • Setting minimum size limit for a window in java swing

    - by shadyabhi
    I have a JFrame which has 3 JPanels in GridBagLayout.. Now, when I minimize a windows, after a certain limit, the third JPanel tends to disappear. I tried setting minimizing size of JFrame using setMinimumSize(new Dimension(int,int)) but no success. The windows can still be minimized. So, I actually want to make a threshhold, that my window cannot be minimized after a certain limit. How can I do so? Code:- import java.awt.Dimension; import javax.swing.JFrame; public class JFrameExample { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(400, 400)); frame.setVisible(true); } } Also: shadyabhi@shadyabhi-desktop:~/java$ java --showversion java version "1.5.0" gij (GNU libgcj) version 4.4.1 Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Usage: gij [OPTION] ... CLASS [ARGS] ... to invoke CLASS.main, or gij -jar [OPTION] ... JARFILE [ARGS] ... to execute a jar file Try `gij --help' for more information. shadyabhi@shadyabhi-desktop:~/java$ Gives me output like

    Read the article

  • Set JTabbedPane width to constant

    - by msp
    I'm implementing an UI in Java Swing. Therefore I use a JTabbedPane. The tabbedPane has no components at startup. When i add a tab to the tabbedpane, the width of the tabbedpane increases, when i remove the tab, the width resizes to the width at the startup. This should not happen. The tabbedpane is placed on a JPanel which has a gridbag layout. Layout code: Container contentPane = mainFrame.getContentPane(); contentPane.setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); // add the component tree initComponentTree(); c.gridx = 0; c.gridy = 0; c.gridheight = 1; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.LINE_START; c.weightx = 1; c.weighty = 1; contentPane.add( componentTree, c ); // add the tabbed pane initTabbedPane(); c.gridx = 1; c.weightx = 10; contentPane.add( tabbedPane, c ); // add the status panel initStatusPanel(); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.LINE_START; c.weightx = 0; c.weighty = 0; contentPane.add( statusPanel, c ); Hope someone can help!

    Read the article

  • update jframe in java or revalidate/repaint/ panel

    - by user1516251
    How to update a java frame with changed content I want to update a frame or just the panel with updated content. What do I use for this Here is where i want to revalidate the frame or repaint mainpanel or whatever will work I have tried a number of things, but none of them have worked. public void actionPerformed(ActionEvent e) { //System.out.println(e.getActionCommand()); if (e.getActionCommand().equals("advance")) { multi--; // Revalidate update repaint here <<<<<<<<<<<<<<<<<<< } else if (e.getActionCommand().equals("reverse")) { multi++; // Revalidate update repaint here <<<<<<<<<<<<<<<<<<< } else { openURL(e.getActionCommand()); } } Here is the whole java file /* * * */ package build; import java.lang.reflect.Method; import javax.swing.JOptionPane; import java.util.Arrays; import java.util.*; import java.util.ArrayList; import javax.swing.*; import javax.swing.AbstractButton; import javax.swing.JScrollPane; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.ImageIcon; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; /* * ButtonDemo.java requires the following files: * images/right.gif * images/middle.gif * images/left.gif */ public class StockTable extends JPanel implements ActionListener { static int multi = 1; int roll = 0; static TextVars textvars = new TextVars(); static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "seamonkey", "galeon", "kazehakase", "mozilla", "netscape" }; JFrame frame; JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right; JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()]; JLabel label[] = new JLabel[textvars.getNumberOfStocks()]; JLabel headlabel, dayspan, namelabel; JRadioButton radioButton; JButton button; JScrollPane scrollpane; int wid = 825; public JPanel createContentPane() { mainpanel = new JPanel(); mainpanel.setPreferredSize(new Dimension(wid, 800)); mainpanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); panel1 = new JPanel(); panel1.setPreferredSize(new Dimension(wid, 25)); c.gridx = 0; c.gridy = 0; c.insets = new Insets(0,0,0,0); mainpanel.add(panel1, c); // Panel 2------------ panel2 = new JPanel(); panel2.setPreferredSize(new Dimension(wid, 51)); c.gridx = 0; c.gridy = 1; c.insets = new Insets(0,0,0,0); mainpanel.add(panel2, c); panel2left = new JPanel(); panel2left.setPreferredSize(new Dimension(270, 51)); c.gridx = 0; c.gridy = 1; c.insets = new Insets(0,0,0,0); panel2.add(panel2left, c); panel2center = new JPanel(); panel2center.setPreferredSize(new Dimension(258, 51)); c.gridx = 1; c.gridy = 1; c.insets = new Insets(0,0,0,0); panel2.add(panel2center, c); panel2right = new JPanel(); panel2right.setPreferredSize(new Dimension(270, 51)); c.gridx = 2; c.gridy = 1; c.insets = new Insets(0,0,0,0); panel2.add(panel2right, c); // ------------------ panel3 = new JPanel(); panel3.setLayout(new GridBagLayout()); scrollpane = new JScrollPane(panel3); scrollpane.setPreferredSize(new Dimension(wid, 675)); c.gridx = 0; c.gridy = 2; c.insets = new Insets(0,0,0,0); mainpanel.add(scrollpane, c); ImageIcon leftButtonIcon = createImageIcon("images/right.gif"); //b1 = new JButton("Disable middle button", leftButtonIcon); //b1.setVerticalTextPosition(AbstractButton.CENTER); //b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales //b1.setMnemonic(KeyEvent.VK_D); //b1.setActionCommand("disable"); //Listen for actions on buttons 1 //b1.addActionListener(this); //b1.setToolTipText("Click this button to disable the middle button."); //Add Components to this container, using the default FlowLayout. //add(b1); headlabel = new JLabel("hellorow1"); c.gridx = 0; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); panel1.add(headlabel, c); radioButton = new JRadioButton("Percentage"); c.gridx = 2; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); panel1.add(radioButton, c); radioButton = new JRadioButton("Days Range"); c.gridx = 3; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); panel1.add(radioButton, c); radioButton = new JRadioButton("Open / Close"); c.gridx = 4; c.gridy = 0; c.insets = new Insets(0, 0, 0,0 ); panel1.add(radioButton, c); button = new JButton("<<"); button.setPreferredSize(new Dimension(50, 50)); button.setActionCommand("reverse"); button.addActionListener(this); c.gridx = 0; c.gridy = 1; c.insets = new Insets(0, 0, 0, 0); panel2left.add(button, c); dayspan = new JLabel("hellorow2"); dayspan.setHorizontalAlignment(JLabel.CENTER); dayspan.setVerticalAlignment(JLabel.CENTER); dayspan.setPreferredSize(new Dimension(270, 50)); c.gridx = 1; c.gridy = 1; c.insets = new Insets(0, 0, 0, 0); panel2center.add(dayspan, c); button = new JButton(">>"); button.setPreferredSize(new Dimension(50, 50)); button.setActionCommand("advance"); button.addActionListener(this); if (multi == 0) { button.setEnabled(false); } else { button.setEnabled(true); } c.gridx = 2; c.gridy = 1; c.insets = new Insets(0, 0, 0, 0); panel2right.add(button, c); int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7; ArrayList<String[]> stocknames = textvars.getStockNames(); ArrayList<String[]> stocks = textvars.getStocks(); for (int column = 0; column < 8; column++) { for (int row = 0; row < textvars.getNumberOfStocks(); row++) { if (column==0) { if (row==0) { namelabel = new JLabel(stocknames.get(0)[0]); namelabel.setVerticalAlignment(JLabel.CENTER); namelabel.setHorizontalAlignment(JLabel.CENTER); namelabel.setPreferredSize(new Dimension(100, 25)); c.gridx = column; c.gridy = row; c.insets = new Insets(0, 0, 0, 0); panel3.add(namelabel, c); } else { stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon); stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER); stknames_btn[row].setActionCommand(stocknames.get(row)[1]); stknames_btn[row].addActionListener(this); stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]); stknames_btn[row].setPreferredSize(new Dimension(100, 25)); c.gridx = column; c.gridy = row; c.insets = new Insets(0, 0, 0, 0); //scrollpane.add(stknames[row], c); panel3.add(stknames_btn[row], c); } } else { label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]); label[row].setBorder(BorderFactory.createLineBorder(Color.black)); label[row].setVerticalAlignment(JLabel.CENTER); label[row].setHorizontalAlignment(JLabel.CENTER); label[row].setPreferredSize(new Dimension(100, 25)); c.gridx = column; c.gridy = row; c.insets = new Insets(0,0,0,0); panel3.add(label[row], c); } } } return mainpanel; } public void actionPerformed(ActionEvent e) { //System.out.println(e.getActionCommand()); if (e.getActionCommand().equals("advance")) { multi--; } else if (e.getActionCommand().equals("reverse")) { multi++; } else { openURL(e.getActionCommand()); } } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = StockTable.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } public static void openURL(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class<?> fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class}); openURL.invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); } else { //assume Unix or Linux boolean found = false; for (String browser : browsers) if (!found) { found = Runtime.getRuntime().exec( new String[] {"which", browser}).waitFor() == 0; if (found) Runtime.getRuntime().exec(new String[] {browser, url}); } if (!found) throw new Exception(Arrays.toString(browsers)); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error attempting to launch web browser\n" + e.toString()); } } int reit = 0; int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1; public int columnMulti(int multi) { reit++; start++; if (reit == textvars.getNumberOfStocks()) { reit = 0; start=start+64; } //start = start - (multi*(textvars.getNumberOfStocks())); return start; } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Stock Table"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. StockTable newContentPane = new StockTable(); //newContentPane.setOpaque(true); //content panes must be opaque //frame.setContentPane(newContentPane); frame.setContentPane(newContentPane.createContentPane()); frame.setSize(800, 800); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

    Read the article

  • Jpanel didn't show rest of it's component

    - by Ali Amiri
    I have jfarame with a button and a JPanel as I named panel, I want after I clicked the button add an inner JPanel to my panel. But this but there is a problem with this! because after adding second panel it didn't add any other panel. my code is: import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.GridLayout; import javax.swing.JTextField; public class DrawImages extends JFrame{ int i; public DrawImages() { JButton btnNewButton = new JButton("New button"); i = 0; getContentPane().add(btnNewButton, BorderLayout.SOUTH); setMinimumSize(new Dimension(1000,150)); final JPanel panel = new JPanel(); panel.setSize(995, 145); getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); final JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setBounds(0, 0, 46, 14); panel.add(lblNewLabel); btnNewButton.addActionListener(new ActionListener() public void actionPerformed(ActionEvent paramActionEvent) { JPanel panel_1 = new JPanel(); //getContentPane().add(panel_1, BorderLayout.NORTH); panel_1.setLayout(null); JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg")); imagelable.setBounds(70, 5, 105, 65); panel_1.add(imagelable); JLabel lblNewLabel_4 = new JLabel("Up Label"); lblNewLabel_4.setBounds(5, 5, 65, 35); panel_1.add(lblNewLabel_4); JLabel lblNewLabel_2 = new JLabel("Down Label"); lblNewLabel_2.setBounds(5, 25, 65, 65); panel_1.add(lblNewLabel_2); lblNewLabel.setText(""+i); panel_1.setBounds(5+170*i, 5, 170+170*i, 70); panel.add(panel_1); i++; } }); panel.setMinimumSize(new Dimension(995,150)); } public static void main(String[]args) { DrawImages drawImages = new DrawImages(); drawImages.setVisible(true); } }

    Read the article

  • How to set BackGround color to a divider in JSplitPane

    - by Sunil Kumar Sahoo
    I have created a divider in JSplitPane. I am unable to set the color of divider. I want to set the color of divider. please help me how to set color of that divider import javax.swing.; import java.awt.; import java.awt.event.*; public class SplitPaneDemo { JFrame frame; JPanel left, right; JSplitPane pane; int lastDividerLocation = -1; public static void main(String[] args) { SplitPaneDemo demo = new SplitPaneDemo(); demo.makeFrame(); demo.frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); demo.frame.show(); } public JFrame makeFrame() { frame = new JFrame(); // Create a horizontal split pane. pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); left = new JPanel(); left.setBackground(Color.red); pane.setLeftComponent(left); right = new JPanel(); right.setBackground(Color.green); pane.setRightComponent(right); JButton showleft = new JButton("Left"); showleft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); if (pane.isShowing()) { lastDividerLocation = pane.getDividerLocation(); } c.remove(pane); c.remove(left); c.remove(right); c.add(left, BorderLayout.CENTER); c.validate(); c.repaint(); } }); JButton showright = new JButton("Right"); showright.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); if (pane.isShowing()) { lastDividerLocation = pane.getDividerLocation(); } c.remove(pane); c.remove(left); c.remove(right); c.add(right, BorderLayout.CENTER); c.validate(); c.repaint(); } }); JButton showboth = new JButton("Both"); showboth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Container c = frame.getContentPane(); c.remove(pane); c.remove(left); c.remove(right); pane.setLeftComponent(left); pane.setRightComponent(right); c.add(pane, BorderLayout.CENTER); if (lastDividerLocation >= 0) { pane.setDividerLocation(lastDividerLocation); } c.validate(); c.repaint(); } }); JPanel buttons = new JPanel(); buttons.setLayout(new GridBagLayout()); buttons.add(showleft); buttons.add(showright); buttons.add(showboth); frame.getContentPane().add(buttons, BorderLayout.NORTH); pane.setPreferredSize(new Dimension(400, 300)); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.pack(); pane.setDividerLocation(0.5); return frame; } } Thanks Sunil kumar Sahoo

    Read the article

  • zoom a JPanel and all of its components

    - by user253530
    I have a big JPanel which holds many TileMapping objects (TileMapping extends JPanel). I want to zoom the big JPanel and all of its components to be scaled aswell. A TileMapping has an image which of course has to be zoomed as well. here is my TileMapping class public class TileMapping extends JPanel { private double zoom = 1.0; private Mapping mapping; private int height; private int width; private int xCoord; private int yCoord; TileMapping(Mapping m, int w, int h, int x, int y) { super(); mapping = m; height = h; width = w; this.xCoord = x; this.yCoord = y; this.setPreferredSize(new Dimension(w, h)); } public int getXcoord() { return xCoord; } public int getYcoord() { return yCoord; } public Mapping getMapping() { return mapping; } public void setMapping(Mapping m) { mapping = m; } public void originalSize() { zoom = 1; } public void zoomIn() { zoom += 0.2; } public void zoomOut() { zoom -= 0.2; } @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; if (mapping.getImage() != null) { BufferedImage bg = mapping.getImage(); g2d.scale(zoom, zoom); g2d.drawImage(bg, 0, 0, width, height, this); } else { g2d.scale(zoom, zoom); this.setBackground(Color.white); } } } I need to know how i should continue this on the main JPanel which is populated using this code: This is part of a MapWindow class. if you carefully read the code you will understand what i'm talking about. Basically this is a Tile MapEditor and I am simulating a Tile as a JPanel which holds the mapping object (mapping is a binding between an ASCII character and an image) you place. private void populateMapPanel(Map map) { GridBagConstraints c = new GridBagConstraints(); mapPanel.setLayout(new GridBagLayout()); for (int i = 0; i < map.getMapGrid().getRows(); i++) { for (int j = 0; j < map.getMapGrid().getColumns(); j++) { tile = new TileMapping(map.getMapItem(i, j), cellSize, cellSize, i, j); tile.setBorder(new LineBorder(Color.black)); tile.addMouseListener(this); tile.addMouseMotionListener(this); c.gridx = i; c.gridy = j; mapPanel.add(tile, c); } } mapPanel.validate(); mapPanel.repaint(); } I need to know how to do the following: 1. When the user presses Zoom In the mapPanel should zoom in and also all the images in the smaller panels. 2. when the user click and drag over the TileMappings an image should be painted on them and this image should get scaled of course if the mapPanel is zoomed. Pseudo code, ideas, hints, java code ...anything would be helpful. Thank you

    Read the article

  • Why does windows XP minimize my swing full screen window on my second screen ?

    - by Laurent K
    Hello dear fellows, In the application I'm developping (in Java/swing), I have to show a full screen window on the second screen of the user. I did this using a code similar to the one you'll find below... Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized... Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows? Thanks for the help, import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JWindow; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Window; import javax.swing.JButton; import javax.swing.JToggleButton; import java.awt.Rectangle; import java.awt.GridBagLayout; import javax.swing.JLabel; public class FullScreenTest { private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35" private JPanel jContentPane = null; private JToggleButton jToggleButton = null; private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37" private JLabel jLabel = null; private Window window; /** * This method initializes jFrame * * @return javax.swing.JFrame */ private JFrame getJFrame() { if (jFrame == null) { jFrame = new JFrame(); jFrame.setSize(new Dimension(474, 105)); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setContentPane(getJContentPane()); } return jFrame; } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getJToggleButton(), null); } return jContentPane; } /** * This method initializes jToggleButton * * @return javax.swing.JToggleButton */ private JToggleButton getJToggleButton() { if (jToggleButton == null) { jToggleButton = new JToggleButton(); jToggleButton.setBounds(new Rectangle(50, 23, 360, 28)); jToggleButton.setText("Show Full Screen Window on 2nd screen"); jToggleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { showFullScreenWindow(jToggleButton.isSelected()); } }); } return jToggleButton; } protected void showFullScreenWindow(boolean b) { if(window==null){ window = initFullScreenWindow(); } window.setVisible(b); } private Window initFullScreenWindow() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gds = ge.getScreenDevices(); GraphicsDevice gd = gds[1]; JWindow window = new JWindow(gd.getDefaultConfiguration()); window.setContentPane(getJFSPanel()); gd.setFullScreenWindow(window); return window; } /** * This method initializes jFSPanel * * @return javax.swing.JPanel */ private JPanel getJFSPanel() { if (jFSPanel == null) { jLabel = new JLabel(); jLabel.setBounds(new Rectangle(18, 19, 500, 66)); jLabel.setText("Hello ! Now, juste open windows explorer and see what happens..."); jFSPanel = new JPanel(); jFSPanel.setLayout(null); jFSPanel.setSize(new Dimension(500, 107)); jFSPanel.add(jLabel, null); } return jFSPanel; } /** * @param args */ public static void main(String[] args) { FullScreenTest me = new FullScreenTest(); me.getJFrame().setVisible(true); } }

    Read the article

  • Delay in displaying contents in JDialog

    - by Yohan
    Please have a look at the following code import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class SendEmailForm extends JDialog { private JLabel to, cc, bcc, subject, account; private JTextField toTxt, ccTxt, bccTxt, subjectTxt; private JTextArea messageTxt; private JButton send; private JComboBox accountBox; private JScrollPane scroll; private GridBagLayout gbl; private GridBagConstraints gbc; public SendEmailForm() { //Declaring instance variables to = new JLabel("To: "); cc = new JLabel("CC: "); bcc = new JLabel("BCC: "); subject = new JLabel("Subject: "); account = new JLabel("Select an Account: "); toTxt = new JTextField(20); ccTxt = new JTextField(20); bccTxt = new JTextField(20); subjectTxt = new JTextField(20); messageTxt = new JTextArea(20, 50); messageTxt.setLineWrap(true); scroll = new JScrollPane(messageTxt); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); accountBox = new JComboBox(); accountBox.addItem("Yahoo"); accountBox.addItem("GMail"); accountBox.addItem("MSN"); //accountBox.addItem("Yahoo"); //accountBox.addItem("Yahoo"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); send = new JButton("Send"); send.addActionListener(new SendButtonAction()); buttonPanel.add(send); //Creating thr GUI //GUI CREATION IS REMOVED IN THIS POST this.setTitle("Send Emails"); this.setVisible(true); this.pack(); this.setLocationRelativeTo(null); this.validate(); } private class SendButtonAction implements ActionListener { public void actionPerformed(ActionEvent ae) { ProgressMonitor pm = new ProgressMonitor(); //Retreiving the user name and password List userData = new ArrayList(); EmailDBConnector emailCon = new EmailDBHandler(); userData = emailCon.getUserNameAndPassword( accountBox.getSelectedItem().toString().trim()); String userName = userData.get(0).toString(); String password = userData.get(1).toString(); System.out.println(userName); System.out.println(password); pm.setVisible(true); SendEmail sendEmail = new SendEmail(toTxt.getText(), userName.trim(), bccTxt.getText(), ccTxt.getText(), accountBox.getSelectedItem().toString().trim(), messageTxt.getText().trim(), password.trim(), subjectTxt.getText()); String result = sendEmail.send(); //pm.dispose(); JOptionPane.showMessageDialog(null, result); } } private class ProgressMonitor extends JDialog { public ProgressMonitor() { this.setLayout(new BorderLayout()); JLabel text = new JLabel("Sending..Please wait..."); this.add(text, "Center"); this.pack(); this.validate(); this.setLocationRelativeTo(null); } } } First, this is an email program. In here, when the JDialog is called, it just opens as a 100% blank window. I have added a JLabel, but it is not there when it is displaying. Anyway, it takes sometime to send the email, after the email is sent, I can see the JLabel in the JDialog. If I take my issue into one sentence, I am calling the JDialog before the email is sent, but it appears blank, after the email is sent, it's content are there! Why is this? Please help!

    Read the article

  • Nothing happen when refreshing the main Frame (JAVA)

    - by Ams
    Hello everyone, I try to show a ( Logged in ) message when a user is succefully connected but nothing happen when a do a repaint(). you can take a look to the code : public class MainFrame extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; private static final int FRAME_HEIGHT = 400; private static final int FRAME_WIDTH = 250; private static final String TITLE = new String("TweeX"); private static String TWITTERID = new String(); private static String TWITTERPW = new String(); private boolean logged = false; private JTextField loginField = new JTextField(10); private JPasswordField passField = new JPasswordField(10); private JButton login = new JButton("Connect"); private GridBagConstraints c = new GridBagConstraints(); private String UserStatus = new String("Please login..."); /* * Constructor ! */ MainFrame() { setSize(FRAME_WIDTH, FRAME_HEIGHT); setTitle(TITLE); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setResizable(false); loginUser(); } /* * Login Forms */ protected void loginUser(){ this.setLayout(new GridBagLayout()); //add Login Fiels + Label c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.insets = new Insets(5,5,5,20); c.gridy = 0; add(new JLabel("Username:"),c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; add(loginField,c); //add Password Fiels + Label c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; add(new JLabel("Password:"),c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; add(passField,c); //add Login button c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 2; add(login,c); //add listener to login button login.addActionListener((ActionListener) this); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 3; add(new JLabel(UserStatus),c); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { TWITTERID = loginField.getText(); TWITTERPW = passField.getText(); Twitter twitter = new TwitterFactory().getInstance(TWITTERID,TWITTERPW); logged = true; try { twitter.verifyCredentials(); } catch (TwitterException e1) { logged = false; } } protected void connect(){ if(logged){ UserStatus = "Loged In :)"; repaint(); } } static public void main(String[] argv) { new MainFrame(); } }

    Read the article

  • Get rid of jfreechart chartpanel unnecessary space

    - by ryvantage
    I am trying to get a JFreeChart ChartPanel to remove unwanted extra space between the edge of the panel and the graph itself. To best illustrate, here's a SSCCE (with JFreeChart installed): public static void main(String[] args) { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 1; gbc.weighty = 1; gbc.gridy = 1; gbc.gridx = 1; panel.add(createChart("Sales", Chart_Type.DOLLARS, 100000, 115000), gbc); gbc.gridx = 2; panel.add(createChart("Quotes", Chart_Type.DOLLARS, 250000, 240000), gbc); gbc.gridx = 3; panel.add(createChart("Profits", Chart_Type.PERCENTAGE, 40.00, 38.00), gbc); JFrame frame = new JFrame(); frame.add(panel); frame.setSize(800, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private static ChartPanel createChart(String title, Chart_Type type, double goal, double actual) { double maxValue = goal * 2; double yellowToGreenNum = goal; double redToYellowNum = goal * .75; DefaultValueDataset dataset = new DefaultValueDataset(actual); JFreeChart jfreechart = createChart(dataset, Math.max(actual, maxValue), redToYellowNum, yellowToGreenNum, title, type); ChartPanel chartPanel = new ChartPanel(jfreechart); chartPanel.setBorder(new LineBorder(Color.red)); return chartPanel; } private static JFreeChart createChart(ValueDataset valuedataset, Number maxValue, Number redToYellowNum, Number yellowToGreenNum, String title, Chart_Type type) { MeterPlot meterplot = new MeterPlot(valuedataset); meterplot.setRange(new Range(0.0D, maxValue.doubleValue())); meterplot.addInterval(new MeterInterval(" Goal Not Met ", new Range(0.0D, redToYellowNum.doubleValue()), Color.lightGray, new BasicStroke(2.0F), new Color(255, 0, 0, 128))); meterplot.addInterval(new MeterInterval(" Goal Almost Met ", new Range(redToYellowNum.doubleValue(), yellowToGreenNum.doubleValue()), Color.lightGray, new BasicStroke(2.0F), new Color(255, 255, 0, 64))); meterplot.addInterval(new MeterInterval(" Goal Met ", new Range(yellowToGreenNum.doubleValue(), maxValue.doubleValue()), Color.lightGray, new BasicStroke(2.0F), new Color(0, 255, 0, 64))); meterplot.setNeedlePaint(Color.darkGray); meterplot.setDialBackgroundPaint(Color.white); meterplot.setDialOutlinePaint(Color.gray); meterplot.setDialShape(DialShape.CHORD); meterplot.setMeterAngle(260); meterplot.setTickLabelsVisible(false); meterplot.setTickSize(maxValue.doubleValue() / 20); meterplot.setTickPaint(Color.lightGray); meterplot.setValuePaint(Color.black); meterplot.setValueFont(new Font("Dialog", Font.BOLD, 0)); meterplot.setUnits(""); if(type == Chart_Type.DOLLARS) meterplot.setTickLabelFormat(NumberFormat.getCurrencyInstance()); else if(type == Chart_Type.PERCENTAGE) meterplot.setTickLabelFormat(NumberFormat.getPercentInstance()); JFreeChart jfreechart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, meterplot, false); return jfreechart; } enum Chart_Type { DOLLARS, PERCENTAGE } If you resize the frame, you can see that you cannot make the edge of the graph go to the edge of the panel (the panels are outlined in red). Especially on the bottom - there is always a gap between the bottom the graph and the bottom of the panel. Is there a way to make the graph fill the entire area? Is there a way to at least guarantee that it is touching one edge of the panel (i.e., it is touching the top and bottom or the left and right) ??

    Read the article

  • Panel is not displaying in JFrame

    - by mallikarjun
    I created a chat panel and added to Jframe but the panel is not displaying. But my sop in the chat panel are displaying in the console. Any one please let me know what could be the problem My Frame public class MyFrame extends JFrame { MyPanel chatClient; String input; public MyFrame() { input = (String)JOptionPane.showInputDialog(null, "Name:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null,null, "Test"); input=input.trim(); chatClient = new MyPanel("localhost",input); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(chatClient); } public static void main(String...args){ new MyFrame(); } } MyPanel: public class MyPanel extends JPanel{ ChatClient chatClient; public MyPanel(String host, String uid) { chatClient= new ChatClient(host,uid); add(chatClient.getChatPanel()); this.setVisible(true); } } chat panel: public class ChatClient { Client client; String name; ChatPanel chatPanel; String hostid; public ChatClient(String host,String uid){ client = new Client(); client.start(); System.out.println("in constructor"); Network.register(client); client.addListener(new Listener(){ public void connected(Connection connection){ System.out.println("in client connected method"); Network.RegisterName registerName = new Network.RegisterName(); registerName.name=name; client.sendTCP(registerName); } public void received(Connection connection,Object object){ System.out.println("in client received method"); if (object instanceof Network.UpdateNames) { Network.UpdateNames updateNames = (Network.UpdateNames)object; //chatFrame.setNames(updateNames.names); System.out.println("got it message"); return; } if (object instanceof Network.ChatMessage) { Network.ChatMessage chatMessage = (Network.ChatMessage)object; //chatFrame.addMessage(chatMessage.text); System.out.println("send it message"); return; } } }); // end of listner name=uid.trim(); hostid=host.trim(); chatPanel = new ChatPanel(hostid,name); chatPanel.setSendListener(new Runnable(){ public void run(){ Network.ChatMessage chatMessage = new Network.ChatMessage(); chatMessage.chatMessage=chatPanel.getSendText(); client.sendTCP(chatMessage); } }); new Thread("connect"){ public void run(){ try{ client.connect(5000, hostid,Network.port); }catch(IOException e){ e.printStackTrace(); } } }.start(); }//end of constructor static public class ChatPanel extends JPanel{ CardLayout cardLayout; JList messageList,nameList; JTextField sendText; JButton sendButton; JPanel topPanel,bottomPanel,panel; public ChatPanel(String host,String user){ setSize(600, 200); this.setVisible(true); System.out.println("Chat panel "+host+"user: "+user); { panel = new JPanel(new BorderLayout()); { topPanel = new JPanel(new GridLayout(1,2)); panel.add(topPanel); { topPanel.add(new JScrollPane(messageList=new JList())); messageList.setModel(new DefaultListModel()); } { topPanel.add(new JScrollPane(nameList=new JList())); nameList.setModel(new DefaultListModel()); } DefaultListSelectionModel disableSelections = new DefaultListSelectionModel() { public void setSelectionInterval (int index0, int index1) { } }; messageList.setSelectionModel(disableSelections); nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } { bottomPanel = new JPanel(new GridBagLayout()); panel.add(bottomPanel,BorderLayout.SOUTH); bottomPanel.add(sendText=new JTextField(),new GridBagConstraints(0,0,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)); bottomPanel.add(sendButton=new JButton(),new GridBagConstraints(1,0,1,1,0,0,GridBagConstraints.CENTER,0,new Insets(0,0,0,0),0,0)); } } sendText.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ sendButton.doClick(); } }); } public void setSendListener (final Runnable listener) { sendButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { if (getSendText().length() == 0) return; listener.run(); sendText.setText(""); sendText.requestFocus(); } }); } public String getSendText () { return sendText.getText().trim(); } public void setNames (final String[] names) { EventQueue.invokeLater(new Runnable(){ public void run(){ DefaultListModel model = (DefaultListModel)nameList.getModel(); model.removeAllElements(); for(String name:names) model.addElement(name); } }); } public void addMessage (final String message) { EventQueue.invokeLater(new Runnable() { public void run () { DefaultListModel model = (DefaultListModel)messageList.getModel(); model.addElement(message); messageList.ensureIndexIsVisible(model.size() - 1); } }); } } public JPanel getChatPanel(){ return chatPanel; } }

    Read the article

  • Java Program Compiles and Runs, but doesn't work

    - by Richard Long
    When I run this program I enter information in a text box, push the search button, but nothing happens. The program just sits there until I press Cntrl C to break it. It looks like it should work, but I can't figure out what is hanging the program up. Here is the code: First class: import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class NameGameFrame extends JFrame { public static String name; static JTextField textfield = new JTextField(20); static JTextArea textarea = new JTextArea(30,30); public static String num; public static String [] fields; public static int [] yearRank; public static boolean match; public static int getInts, marker, year, max; public static void main( String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Name Game"); frame.setLocation(500,400); frame.setSize(800,800); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JLabel label = new JLabel("Enter the Name or Partial Name to search:"); c.gridx = 0; c.gridy = 0; c.insets = new Insets(2,2,2,2); panel.add(label,c); c.gridx = 0; c.gridy = 1; panel.add(textarea,c); JButton button = new JButton("Search"); c.gridx = 1; c.gridy = 1; panel.add(button,c); c.gridx = 1; c.gridy = 0; panel.add(textfield,c); frame.getContentPane().add(panel, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { name = textfield.getText(); java.io.File file = new java.io.File("namesdata.txt"); try { Scanner input = new Scanner(file); num = input.nextLine(); NameRecord nr = new NameRecord(name); while (input.hasNext()) { if(match = num.toLowerCase().contains(name.toLowerCase())) { nr.getRank(); nr.getBestYear(marker); } } } catch(FileNotFoundException e) { System.err.format("File does not exist\n"); } textarea.setText(fields[0]); } }); } } This is the second class: import java.io.*; import java.util.*; public class NameRecord { public NameRecord( String name) { } public static int getBestYear(int marker) { switch (marker) { case 1: year = 1900; break; case 2: year = 1910; break; case 3: year = 1920; break; case 4: year = 1930; break; case 5: year = 1940; break; case 6: year = 1950; break; case 7: year = 1960; break; case 8: year = 1970; break; case 9: year = 1980; break; case 10: year = 1990; break; case 11: year = 2000; break; } return year; } public static int getRank() { fields = num.split(" "); max = 0; for (int i = 1; i<12; i++) { getInts = Integer.parseInt(fields[i]); if(getInts>max) { max = getInts; marker = i; } } return max; } }

    Read the article

  • How to send audio data from Java Applet to Rails controller

    - by cooldude
    Hi, I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save. So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR : LAVF_header: av_open_input_stream() failed while playing with the mplayer. Here is the Java Code: package networksocket; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JApplet; import java.net.*; import java.io.*; import java.awt.event.*; import java.awt.*; import java.sql.*; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.util.Properties; import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager; import sun.awt.HorizBagLayout; import sun.awt.VerticalBagLayout; import sun.misc.BASE64Encoder; /** * * @author mukand */ public class Urlconnection extends JApplet implements ActionListener { /** * Initialization method that will be called after the applet is loaded * into the browser. */ public BufferedInputStream in; public BufferedOutputStream out; public String line; public FileOutputStream file; public int bytesread; public int toread=1024; byte b[]= new byte[toread]; public String f="FINISH"; public String match; public File fileopen; public JTextArea jTextArea; public Button refreshButton; public HttpURLConnection urlConn; public URL url; OutputStreamWriter wr; BufferedReader rd; @Override public void init() { // TODO start asynchronous download of heavy resources //textField= new TextField("START"); //getContentPane().add(textField); JPanel p = new JPanel(); jTextArea= new JTextArea(1500,1500); p.setLayout(new GridLayout(1,1, 1,1)); p.add(new JLabel("Server Details")); p.add(jTextArea); Container content = getContentPane(); content.setLayout(new GridBagLayout()); // Used to center the panel content.add(p); jTextArea.setLineWrap(true); refreshButton = new java.awt.Button("Refresh"); refreshButton.reshape(287,49,71,23); refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12)); refreshButton.addActionListener(this); add(refreshButton); Properties properties = System.getProperties(); properties.put("http.proxyHost", "netmon.iitb.ac.in"); properties.put("http.proxyPort", "80"); } @Override public void actionPerformed(ActionEvent e) { try { url = new URL("http://localhost:3000/audio/audiorecieve"); urlConn = (HttpURLConnection)url.openConnection(); //String login = "mukandagarwal:rammstein$"; //String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes()); //urlConn.setRequestProperty("Proxy-Authorization",login); urlConn.setRequestMethod("POST"); // urlConn.setRequestProperty("Content-Type", //"application/octet-stream"); //urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Length", "" + // Integer.toString(urlParameters.getBytes().length)); urlConn.setRequestProperty("Content-Language", "UTF-8"); urlConn.setDoOutput(true); urlConn.setDoInput(true); byte bread[]=new byte[2048]; int iread; char c; String data=URLEncoder.encode("key1", "UTF-8")+ "="; //String data="key1="; FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3"); while((iread=fileread.read(bread))!=-1) { //data+=(new String()); /*for(int i=0;i<iread;i++) { //c=(char)bread[i]; System.out.println(bread[i]); }*/ data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));// // data+=new String(bread,iread); } //urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length)); System.out.println(data); //data+=URLEncoder.encode("mukand", "UTF-8"); //data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); //data="key1="; wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream(); //if((iread=fileread.read(bread))!=-1) // wr.write(bread,0,iread); wr.write(data); wr.flush(); fileread.close(); jTextArea.append("Send"); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = rd.readLine()) != null) { jTextArea.append(line); } wr.close(); rd.close(); //jTextArea.append("click"); } catch (MalformedURLException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void start() { } @Override public void stop() { } @Override public void destroy() { } // TODO overwrite start(), stop() and destroy() methods } Here is the Rails controller function for recieving: def audiorecieve puts "///////////////////////////////////////******RECIEVED*******////" puts params[:key1]#+" "+params[:key2] data=params[:key1] #request.env('RAW_POST_DATA') file=File.new("audiodata.ogg", 'w') file.write(data) file.flush file.close puts "////**************DONE***********//////////////////////" end Please reply quickly

    Read the article

  • Multiple Components in a JTree Node Renderer & Node Editor

    - by Samad Lotia
    I am attempting to create a JTree where a node has several components: a JPanel that holds a JCheckBox, followed by a JLabel, then a JComboBox. I have attached the code at the bottom if one wishes to run it. Fortunately the JTree correctly renders the components. However when I click on the JComboBox, the node disappears; if I click on the JCheckBox, it works fine. It seems that I am doing something wrong with how the TreeCellEditor is being set up. How could I resolve this issue? Am I going beyond the capabilities of JTree? Here's a quick overview of the code I have posted below. The class EntityListDialog merely creates the user interface. It is not useful to understand it other than the createTree method. Node is the data structure that holds information about each node in the JTree. All Nodes have a name, but samples may be null or an empty array. This should be evident by looking at EntityListDialog's createTree method. The name is used as the text of the JCheckBox. If samples is non-empty, it is used as the contents of the JCheckBox. NodeWithSamplesRenderer renders Nodes whose samples are non-empty. It creates the complicated user interface with the JPanel consisting of the JCheckBox and the JComboBox. NodeWithoutSamplesRenderer creates just a JCheckBox when samples is empty. RendererDispatcher decides whether to use a NodeWithSamplesRenderer or a NodeWithoutSamplesRenderer. This entirely depends on whether Node has a non-empty samples member or not. It essentially functions as a means for the NodeWith*SamplesRenderer to plug into the JTree. Code listing: import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.tree.*; public class EntityListDialog { final JDialog dialog; final JTree entitiesTree; public EntityListDialog() { dialog = new JDialog((Frame) null, "Test"); entitiesTree = createTree(); JScrollPane entitiesTreeScrollPane = new JScrollPane(entitiesTree); JCheckBox pathwaysCheckBox = new JCheckBox("Do additional searches"); JButton sendButton = new JButton("Send"); JButton cancelButton = new JButton("Cancel"); JButton selectAllButton = new JButton("All"); JButton deselectAllButton = new JButton("None"); dialog.getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JPanel selectPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); selectPanel.add(new JLabel("Select: ")); selectPanel.add(selectAllButton); selectPanel.add(deselectAllButton); c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(selectPanel, c); c.gridx = 0; c.gridy = 1; c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(0, 5, 0, 5); dialog.getContentPane().add(entitiesTreeScrollPane, c); c.gridx = 0; c.gridy = 2; c.weightx = 1.0; c.weighty = 0.0; c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(pathwaysCheckBox, c); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonsPanel.add(sendButton); buttonsPanel.add(cancelButton); c.gridx = 0; c.gridy = 3; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; dialog.getContentPane().add(buttonsPanel, c); dialog.pack(); dialog.setVisible(true); } public static void main(String[] args) { EntityListDialog dialog = new EntityListDialog(); } private static JTree createTree() { DefaultMutableTreeNode root = new DefaultMutableTreeNode( new Node("All Entities")); root.add(new DefaultMutableTreeNode( new Node("Entity 1", "Sample A", "Sample B", "Sample C"))); root.add(new DefaultMutableTreeNode( new Node("Entity 2", "Sample D", "Sample E", "Sample F"))); root.add(new DefaultMutableTreeNode( new Node("Entity 3", "Sample G", "Sample H", "Sample I"))); JTree tree = new JTree(root); RendererDispatcher rendererDispatcher = new RendererDispatcher(tree); tree.setCellRenderer(rendererDispatcher); tree.setCellEditor(rendererDispatcher); tree.setEditable(true); return tree; } } class Node { final String name; final String[] samples; boolean selected; int selectedSampleIndex; public Node(String name, String... samples) { this.name = name; this.selected = false; this.samples = samples; if (samples == null) { this.selectedSampleIndex = -1; } else { this.selectedSampleIndex = 0; } } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public String toString() { return name; } public int getSelectedSampleIndex() { return selectedSampleIndex; } public void setSelectedSampleIndex(int selectedSampleIndex) { this.selectedSampleIndex = selectedSampleIndex; } public String[] getSamples() { return samples; } } interface Renderer { public void setForeground(final Color foreground); public void setBackground(final Color background); public void setFont(final Font font); public void setEnabled(final boolean enabled); public Component getComponent(); public Object getContents(); } class NodeWithSamplesRenderer implements Renderer { final DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel(); final JPanel panel = new JPanel(); final JCheckBox checkBox = new JCheckBox(); final JLabel label = new JLabel(" Samples: "); final JComboBox comboBox = new JComboBox(comboBoxModel); final JComponent components[] = {panel, checkBox, comboBox, label}; public NodeWithSamplesRenderer() { Boolean drawFocus = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon"); if (drawFocus != null) { checkBox.setFocusPainted(drawFocus.booleanValue()); } for (int i = 0; i < components.length; i++) { components[i].setOpaque(true); } panel.add(checkBox); panel.add(label); panel.add(comboBox); } public void setForeground(final Color foreground) { for (int i = 0; i < components.length; i++) { components[i].setForeground(foreground); } } public void setBackground(final Color background) { for (int i = 0; i < components.length; i++) { components[i].setBackground(background); } } public void setFont(final Font font) { for (int i = 0; i < components.length; i++) { components[i].setFont(font); } } public void setEnabled(final boolean enabled) { for (int i = 0; i < components.length; i++) { components[i].setEnabled(enabled); } } public void setContents(Node node) { checkBox.setText(node.toString()); comboBoxModel.removeAllElements(); for (int i = 0; i < node.getSamples().length; i++) { comboBoxModel.addElement(node.getSamples()[i]); } } public Object getContents() { String title = checkBox.getText(); String[] samples = new String[comboBoxModel.getSize()]; for (int i = 0; i < comboBoxModel.getSize(); i++) { samples[i] = comboBoxModel.getElementAt(i).toString(); } Node node = new Node(title, samples); node.setSelected(checkBox.isSelected()); node.setSelectedSampleIndex(comboBoxModel.getIndexOf(comboBoxModel.getSelectedItem())); return node; } public Component getComponent() { return panel; } } class NodeWithoutSamplesRenderer implements Renderer { final JCheckBox checkBox = new JCheckBox(); public NodeWithoutSamplesRenderer() { Boolean drawFocus = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon"); if (drawFocus != null) { checkBox.setFocusPainted(drawFocus.booleanValue()); } } public void setForeground(final Color foreground) { checkBox.setForeground(foreground); } public void setBackground(final Color background) { checkBox.setBackground(background); } public void setFont(final Font font) { checkBox.setFont(font); } public void setEnabled(final boolean enabled) { checkBox.setEnabled(enabled); } public void setContents(Node node) { checkBox.setText(node.toString()); } public Object getContents() { String title = checkBox.getText(); Node node = new Node(title); node.setSelected(checkBox.isSelected()); return node; } public Component getComponent() { return checkBox; } } class NoNodeRenderer implements Renderer { final JLabel label = new JLabel(); public void setForeground(final Color foreground) { label.setForeground(foreground); } public void setBackground(final Color background) { label.setBackground(background); } public void setFont(final Font font) { label.setFont(font); } public void setEnabled(final boolean enabled) { label.setEnabled(enabled); } public void setContents(String text) { label.setText(text); } public Object getContents() { return label.getText(); } public Component getComponent() { return label; } } class RendererDispatcher extends AbstractCellEditor implements TreeCellRenderer, TreeCellEditor { final static Color selectionForeground = UIManager.getColor("Tree.selectionForeground"); final static Color selectionBackground = UIManager.getColor("Tree.selectionBackground"); final static Color textForeground = UIManager.getColor("Tree.textForeground"); final static Color textBackground = UIManager.getColor("Tree.textBackground"); final JTree tree; final NodeWithSamplesRenderer nodeWithSamplesRenderer = new NodeWithSamplesRenderer(); final NodeWithoutSamplesRenderer nodeWithoutSamplesRenderer = new NodeWithoutSamplesRenderer(); final NoNodeRenderer noNodeRenderer = new NoNodeRenderer(); final Renderer[] renderers = { nodeWithSamplesRenderer, nodeWithoutSamplesRenderer, noNodeRenderer }; Renderer renderer = null; public RendererDispatcher(JTree tree) { this.tree = tree; Font font = UIManager.getFont("Tree.font"); if (font != null) { for (int i = 0; i < renderers.length; i++) { renderers[i].setFont(font); } } } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { final Node node = extractNode(value); if (node == null) { renderer = noNodeRenderer; noNodeRenderer.setContents(tree.convertValueToText( value, selected, expanded, leaf, row, false)); } else { if (node.getSamples() == null || node.getSamples().length == 0) { renderer = nodeWithoutSamplesRenderer; nodeWithoutSamplesRenderer.setContents(node); } else { renderer = nodeWithSamplesRenderer; nodeWithSamplesRenderer.setContents(node); } } renderer.setEnabled(tree.isEnabled()); if (selected) { renderer.setForeground(selectionForeground); renderer.setBackground(selectionBackground); } else { renderer.setForeground(textForeground); renderer.setBackground(textBackground); } renderer.getComponent().repaint(); renderer.getComponent().invalidate(); renderer.getComponent().validate(); return renderer.getComponent(); } public Component getTreeCellEditorComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { return getTreeCellRendererComponent( tree, value, true, expanded, leaf, row, true); } public Object getCellEditorValue() { return renderer.getContents(); } public boolean isCellEditable(final EventObject event) { if (!(event instanceof MouseEvent)) { return false; } final MouseEvent mouseEvent = (MouseEvent) event; final TreePath path = tree.getPathForLocation( mouseEvent.getX(), mouseEvent.getY()); if (path == null) { return false; } Object node = path.getLastPathComponent(); if (node == null || (!(node instanceof DefaultMutableTreeNode))) { return false; } DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node; Object userObject = treeNode.getUserObject(); return (userObject instanceof Node); } private static Node extractNode(Object value) { if ((value != null) && (value instanceof DefaultMutableTreeNode)) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); if ((userObject != null) && (userObject instanceof Node)) { return (Node) userObject; } } return null; } }

    Read the article

< Previous Page | 1 2