Resizing JFrame with a Jbutton click

I've witten a simple GUI program that if you click on one button it increases the size of the JFrame and the other button will decrease it. The problem is I tried using ComponentResize() putting a listener on the buttons,but it wouldn't work. Anybody with an idea of how I could do this?

try this code
public void actionListener (ActionEvent e)
       int increment = 20;
       frame.setBounds (0,0,frame.getWidth()+increment,frame.getWidth()+increment);
}

Similar Messages

  • Having Trouble Closing a JFrame With a Button Click in Swing

    I am brand new to Java so this is probably something really stupid.
    On my main form I have a table displaying records from a database. When you double click a record, it pops up a second form showing the details of that record. You can then edit the data in this second form and click a "save" button which saves the data to the database. I want this button to also close that second form, however in the button click event, the second form variable is null.
    Here is some code showing the basic concept:
    public class SampleForm {
        private JButton  saveJobButton;
        private JFrame frame;
        private JFrame editDetailFrame;
        public static void main(String[] args) {
            SampleForm sample = new SampleForm();
            sample.createMainFrame();
        public void createMainFrame() {
            frame = new JFrame();
            JComponent panel = buildPanel(); 
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(panel); 
            frame.pack();
            frame.setVisible(true);
        public void createEditFrame() {
            editDetailFrame = new JFrame();
            editDetailFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            JComponent editPanel = new SampleForm().buildDetailPanel();
            editDetailFrame.getContentPane().add(editPanel);
            editDetailFrame.pack();
            editDetailFrame.setVisible(true);
            editDetailFrame.validate();
    // save button
        private JButton getSaveJobButton() {
            if (saveJobButton == null) {
                saveJobButton = new JButton();
                saveJobButton.setText("Save Job");
                saveJobButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                       .. saves data to database.
                        // here is where I thought the dispose() should go but the editDetailFrame is null at this point.
                        editDetailFrame.dispose();
            return saveJobButton;
        }Any assistance would be much appreciated.

    That handles the NullPointer, but still doesn't close my second Frame. The editDetailFrame should not be null at this point as I am clicking a button on the editDetailFram itself so I think the problem is that I just don't have a reference to the actual object at that point and my variable is just an empty one.

  • Selecting checkbox through a JButton click in JFrame

    i am trying to change the state of the check box in a JFrame through a JButton click, using the getsource() method.
    if (e.getSource()==johnButton){
    // Set the state of the checkbox to on
    checkbox.setSelected(true);
    i have also tried using isSelected().
    there is no error in the programme, how ever it doesn't work for me.

    Must be
    if(e.getSource()== JCheckbox)
    do whatever
    However, a better way if you had many checkboxs
    JCheckbox b = new JCheckbox(...);
    b.addActionListener(this);
    b.setActionCommand("MyChkBx");
    public void actionPerformed(ActionEvent e)
    String cmd = e.getActionEvent();
    if(cmd.equals("MyChkBx"))
    do whatever
    }

  • JFrame with JDialog question

    Hi
    I have a JFrame that have a JButton on it. This button have an actionlistener which the inner class of JFrame. When user click on the button, it should pop up a JDialog with modal turn on. How can I pass the Frame to the JDialog so that I can set the modal??
    Thanks..

    Keep a reference of the frame in ur class and create the dialog with this reference

  • Disabling normal JButton click behaviour for double click

    This seems quite a poser.
    Basically I have a test JButton for testing double click speed. This is in a dialog with the JButton and a JSlider.
    I have some code which detects the double click, I add this as using 'addMouseListener()', but I need to disable the normal single click action of the JButton to replace it by the double click code calling 'doClick()'.
    How do I disable the normal single click functionality ?
    I have looked through the SDK source but cannot fathom the normal behaviour of the event mechanism.
    Many thanks in advance.
    Aaron

    Here's an entire program. When I run it, it only catches doubleclicksimport javax.swing.*;
    import java.awt.event.*;
    public class Test {
      public static void main(String[] args) {
        TestFrame testFrame = new TestFrame("Test");
        testFrame.pack();
        testFrame.setSize(200,200);
        testFrame.show();
    class TestFrame extends JFrame {
      public TestFrame(String Title) {
        super(Title);
        JPanel myContent = (JPanel)getContentPane();
        JButton myButton = new JButton("Hello");
        myContent.add(myButton);
        myButton.addMouseListener(new MouseAdapter() {
          public void mouseReleased(MouseEvent me) {
         if (me.getClickCount()==2) System.out.println("DoubleClick!!");
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); }
    }

  • Remove component from JFrame with absolute layout

    I have a JFrame and JPanel inside the JFrame with absolute layout. I wanted to have a button when clicked the JPanel will be removed. I called jFrame.remove(jPanel);
    jFrame.repaint();
    jFrame.validate();
    I can't call jFrame.revalidate(), since JFrame doesn't provide revalidate() method. I try everything, but I can't get that JPanel removed. Could somebody help me please. Oh I tried jPanel.setBounds( 0,0,0,0); and the jPanel is disappeared, but I don't think this is the right solution. Is my problem with the absolute layout?
    Thanks

    public class MainGame
         public void game()
              GridBagLayout gridBagLayout = new GridBagLayout();
              GridBagConstraints constraints = new GridBagConstraints();
              final MainFrame mainFrame = new MainFrame();
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              mainFrame.setLayout( gridBagLayout );
              JPanel mainGamePanel = new JPanel();
              mainGamePanel.setLayout( new BorderLayout() );
              mainGamePanel.setBackground( Color.black );
              final Room mainEntrance = new Room( "at the main entrance of the deep forest" );
              mainEntrance.setBackground( Color.white );
              mainEntrance.setLayout( null );
              mainEntrance.setExit( Direction.UP, null );
              mainGamePanel.add( mainEntrance, BorderLayout.CENTER );
    //          c.fill = GridBagConstraints.CENTER;
              constraints.ipady = 800;      //make this component tall
              constraints.ipadx = 600;
              constraints.anchor = GridBagConstraints.WEST;
              constraints.gridx = 0;
              constraints.gridy = 0;
              gridBagLayout.setConstraints( mainGamePanel, constraints );
              mainFrame.getContentPane().add( mainGamePanel );
              thePlayer = new Human( "Cloud" , "The player" );
              thePlayer.setMaximumWeight( MAXIMUM_WEIGHT );
              thePlayer.setImage( Constants.CHARACTER_FRONT );
              thePlayer.setBounds(0 , 0, 40, 30 );
              thePlayer.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( thePlayer );
              apple = new EdibleItem( "apple" , "Give more 10 HP" );
              apple.setHp( 100 );
              apple.setImage( Constants.APPLE );
              apple.setBounds( 40, 0, 40, 30 );
              apple.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( apple );
              thePlayer.addItem( apple );
              apple1 = new JPanelWithBackground();
              apple1.setImage( Constants.APPLE );
              apple1.setBounds( 80, 60, 40, 30 );
              apple1.setBorder( BorderFactory.createLineBorder( Color.black ) );
              mainEntrance.add( apple1 );
    //          final Room forest = new Room( "at the main entrance of the deep forest" );
    //          forest.setBounds( 0, 0, 800, 600 );
    //          forest.setBackground( Color.white );
    //          forest.setLayout( null );
    //          forest.setExit( Direction.UP, null );
    //          // Add to list
              listOfItems.add( apple );
              listOfItems.add( apple1 );
               * Main Control Panel to control character and actions
              JPanel controlPanel = new JPanel();
              controlPanel.setBackground( Color.black );
              controlPanel.setBounds( 1000, 0, 600, 600 );
              controlPanel.setLayout( new GridLayout( 0, 1 ) );
              JButton eatButton = new JButton( "EAT" );
              // Set this button to setFocusable(false) to prevent this button being focused
              // So the focus will stay at JFrame
              eatButton.setFocusable( false );
              eatButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        JPanelWithBackground currentObject = mainGame.getFacingObject();
                        if( currentObject instanceof EdibleItem )
                             //EdibleItem apple = ( EdibleItem )currentObject;
              controlPanel.add( eatButton );
              JButton attackButton = new JButton( "ATTACK" );
              attackButton.setFocusable( false );
              attackButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        System.out.println( "Remove" );
                        mainFrame.getContentPane().remove( mainEntrance );
                        mainEntrance.setBounds( 0,0,0,0);
    //                    mainFrame.add( forest );
                        mainFrame.validate();
                        mainFrame.repaint();
              controlPanel.add( attackButton );
              mainFrame.setVisible( true );
              mainFrame.requestFocusInWindow();
    }I know that my code is a mess, because it is connected with many classes and the quality of the format is not very good. But I will refactor it later when I solved the problem.
    The problem is I have a JPanel with a character and an apple in it. I could not use any other layout, I have to use absolute layout, because I the user can control the character but arrow keys. And the character moves in pixels.
    Here what I wanted to do.
    final Room mainEntrance = new Room( "at the main entrance of the deep forest" );
              mainEntrance.setBackground( Color.white );
              mainEntrance.setLayout( null );
              mainEntrance.setExit( Direction.UP, null );Room extends JPanel, I wanted to delete this panel when I clicked this button
              JButton attackButton = new JButton( "ATTACK" );
              attackButton.setFocusable( false );
              attackButton.addActionListener( new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent e)
                        System.out.println( "Remove" );
                        mainFrame.getContentPane().remove( mainEntrance );
                        mainEntrance.setBounds( 0,0,0,0);
    //                    mainFrame.add( forest );
                        mainFrame.validate();
                        mainFrame.repaint();
              controlPanel.add( attackButton );Like I said before, I tried validate, repaint and setBounds to all 0s. Nothing happened with the Room class. How do I delete that Room.
    Thank you so much.

  • How do I replace one JPanel on a JFrame with another?

    I want to replace one JPanel on a JFrame with a different JPanel when the user clicks on a certain menu item. The menu item is working corrrectly but I cant seem to repaint / refresh the component.
    My code is as follows:
    c.add(knotPanel, BorderLayout.CENTER);
    c.add(stepPanel, BorderLayout.NORTH);
         if (stepChoice != 9) {
         c.remove(ownPanel);
         c.add(lessonPanel, BorderLayout.EAST);
         else {
         c.remove(lessonPanel);
         c.add(ownPanel, BorderLayout.EAST);
         c.invalidate();
         c.validate();
         c.update(c.getGraphics());
    Any ideas?

    I think you should use CardLayout manager.
    With CardLayout you can switch beetwen JPanels without removing or adding.

  • Creating tables with a button click

    can anyone give me a sample code for creating multiple tables in a scrollpane
    with a button click.
    Thanks

    Here is an example that returns a JTable in a JScrollPane in a JInternalFrame:
    import java.awt.*;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import java.awt.GridLayout;
    public class TablaJ extends JPanel{
         public TablaJ(){
         public TablaJ(String data[][], String columnNames[]){
             super(new GridLayout(1,0));
             final JTable table = new JTable(data, columnNames);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
        static JInternalFrame crearFrameConTabla(String data[][], String columnNames[], String tabla) {
            //Create and set up the window.
            JInternalFrame frame = new JInternalFrame(tabla,true,true,true,true);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            //Create and set up the content pane.
            TablaJ newContentPane = new TablaJ(data, columnNames);
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            return frame;
    }

  • Resizing JFrames and JPanels !!!

    Hi Experts,
    I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
    My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
    My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
    Plese guide me, how should i do this ...
    Thanknig Java Community,
    Dhwanit Shah

    Hey there, thanx for your kind intereset.
    Here is sample code .
    In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
    I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    public class FramePanel extends JFrame {
    JPanel contentPane;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    public FramePanel() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    FramePanel framePanel = new FramePanel();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(gridBagLayout1);
    this.setSize(new Dimension(296, 284));
    this.setTitle("Frame and Panel Together");
    MyPanel myPanel = new MyPanel();
    this.getContentPane().add(myPanel);
    this.setVisible(true);
    class MyPanel extends JPanel {
    public MyPanel() {
    this.setSize(200,200);
    this.setLayout(new FlowLayout());
    this.setBackground(Color.black);
    this.setVisible(true);
    this.add(new JButton("Dhwanit Shah"));
    I think i might explained my problem
    Dhwanit Shah
    [email protected]

  • Resizing radius with keyboard?

    Is there any way to resize the radius of the circe in places with the keyboard? I experienced a couple of times, some lag while trying to resize it with the mouse, and that lag while the mouse was clicked, it converted on the circle covering the whole planet. And you know what happens when some circles overlap others. Well, after fixing the places for more than 6k photos twice, I'm afraid of resizing those circles again.
    Yesterdey, while I tried to resize one of those circles with the mouse (I was playing with fire, yes) I experienced again that lag on iphoto -which takes about 2 seconds-. So I decided to shut down the computer before everything came back to normal and, ****** all my places.
    So, again, my question is if there any way to resize it with the keyboard, so, if I have that lag again, i will no suffer any problem.
    Thanks!
    Nicolás

    I wish there was a solution to this resizing of the blue circle.
    It seems to take on a mind of its own and swallow up all the previous hard work.
    If you want a location, "Where I work" and a location across the road, "Best coffee in the world", it will always swallow up the first location. That has to be addressed.
    I use locations for landscape and wildlife, sometimes the locations are within 50 yards or more of each other.
    My work around has been to set a new location about 500 yards or more from its final location, then when I've clicked the yellow pin to red, go to Manage my Places.
    Highlight the new location, it goes yellow pin and blue circle, I then pull the blue circle in as tight as I can get it to the pin, then move the yellow pin to the location it should be at.
    That way it doesn't swallow up the "Where I work", "Best coffee in town" and "Drinks are on the house tavern".
    Not much of a work around, but it is starting to reduce the number of tablets I have to take to work with Places.
    If you have several locations quite close and are not zoomed in, then they show as some generic label, like the suburb or other important location, which used to drive me crazy, until I zoomed in and all was well.
    Another issue seems to be that the blue circle is able to reset itself, but I have to put most of that down to operator error as I cannot figure out what sequences causes it to become large and swallow up 3 or 4 close locations.
    Any other Places taming ideas?
    Regards
    David

  • Draw with single mouse click, help me!!!!

    I am using this code - as you understood from it- to paint with the mouse click.
    please help me either by completing it or by telling me what to do.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Hello extends JFrame{
         Graphics g;
         ImageIcon icon = new ImageIcon("hello.gif");
         public Hello(){
              super("Hello");
              setSize(200, 200);
              addMouseListener(
                   new MouseAdapter(){
                        public void mouseClicked(MouseEvent e){
                             icon.paintIcon(Hello.this, g, e.getX(), e.getY());
                             g.fillRect(10, 40, 10, 80);
                             JOptionPane.showMessageDialog(Hello.this, e.getX() + ", " + e.getY());
                             //repaint();
         // i have tried to place this listener in the paint method, but no way out.
              setVisible(true);
         public void paint(final Graphics g){
              this.g = g;
              icon.paintIcon(this, g, 100, 50);
         public static void main(String[] args){
              new Hello();
    **

    You can't save a graphics object like that and then paint on it.
    What you need is to use a BufferedImage, paint on that, and then paint that to the screen.
    See my paintarea class. You are welcome to use + modify this class as well as take any code snippets to fit into whatever you have but please add a comment where ever you've incorporated stuff from my class
    PaintArea.java
    ===========
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • JFrames with only the close button

    I have been writing a notepad as my first java project and have done most things but cant seem to fix this: coding a JFrame with only the close button. Most of us know that when you click Help > About... a window pops up describing the company that wrote the software.
    Please help....

    I have been writing a notepad as my first java
    project and have done most things but cant seem to
    fix this: coding a JFrame with only the close button.
    Most of us know that when you click Help > About... a
    window pops up describing the company that wrote the
    software.
    Please help....so whats the problem? you're asking if a person clicks on help->about then a description dialog box should pop up describing the company right? you can use JDialog or a popupmenu. look at the swing tutorial at sun

  • How to close a window with a jbutton?

    hi all!
    im have a login box created with jframe,
    what i want is when i press the submit button and if authentication is success
    i'd like to close the jframe of my login box and open a new window.
    how can i close a jframe window with a jbutton?

    to close the window you can add an anynomous class like this:
    yourButton.addActionListener(
          new ActionListener() {
                  public void actionPerformed( ActionEvnet e ) {
                        System.eixt(0);
    );That's all Buddy, Enjoy

  • JFrame with out icon buttons

    Hi all,
    Is there a way to make a JFram with out the buttons at the upper left and upper right (unix), the ones that min/max the frams on the right and the
    pull down on the left ?
    Also, I know you can make the JFrame not resizable but can you lock it in place in the screen so users can not move it around ?
    Thanks
    Pat
    IMS Field Applications

    Frame.setUndecorated(true); // JFrame inherits this methodI don't know if it works with Unix, but on windows this command removes the border from the Frame or JFrame. The buttons vanish together with the border, and since there is no border to drag, the JFrame is neither movable nor resizable. Another command that makes (decorated) Frames unresizable is
    Frame.setResizable(false);

  • Resizing JFrame

    I have a JFrame with many panels and components, and every time I manually resize it, the textArea seems to resize okay, butthe rest of the buttons remain where they are, it's quite a pain. What doI do?
    (this is a Swing question but no one in Swing seems to have answered it, sorry)

    Use GridBagLayout
    Use the following method
    <CODE>
         // this is a helper method for GridBagConstraint Layout
         public void addComp(Component comp,Container cont, GridBagLayout gb1,GridBagConstraints gbc,int row,int col, int numRows, int numCols, double weightx, double weighty,int theAnchor)
              gbc.gridx = col;
              gbc.gridy = row;
              gbc.gridwidth = numCols;
              gbc.gridheight = numRows;
              gbc.weightx = weightx;
              gbc.weighty = weighty;
              gbc.anchor = theAnchor;
              cont.add(comp,gbc);
    <CODE>
    Then use the following line anytime you want to place a component
         addComp(theComponent,theJFrame,gb1,gbc,column,row,1,1,1,1,gbc.WEST);
    Look up GridBAgConstraint and you will find other options for the last one eg (gbc.NORTHEAST , gbc.CENTER)
    At the start declare
    <CODE>
              GridBagLayout gb1 = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              setLayout(gb1);
    <CODE>
    Sorry about the indentation!! Hope this helps you.i found this very useful and you can arrange components exactly the way you want,let me know if it is helpful

Maybe you are looking for