• I'm disagree with java.util.Timer in Java7/8 for AWT/Swing based GUI

  • it could be possible by to call firePropertyChange from java.util.Timer

  • standard is (inaccurate) Swing Timer
  • (OP wrote) "I started rezing evrything by screen width, example" its about getPreferredSize and together with stopping to use draw() instead of paint/paintComponent in 21th. century

I want to copy TextArea text to a File... == for me (including properties from NativeOS, newline, tab, .....) is JTextArea.write

wrong design, wrong notifiers, most important is repaint(); inside paint/PaintComponent (repaint from itself) caused endless loop with high CPU and GPU usage, missing there stop repainting for contianer or super.paint() as 1st code line in paint, otherwise nothing will be repainted correctly, only nice flickering

  • wrong, not (enless loop = while), you have to add counter inside ActionPerformed,

  • there to a) increase counter, and b) getText from e.getSource,

  • if(counter == 3) to test if(passCode.equals(input)),
  • use JToggleButtons in loop, add ActionListener (already used)

  • you created a new Scanner in every..., how did you want to put that together, remove every code lines in ActionListener, only append String value from e.getSource, there no need to test for every Objects, don't to complicate simple things, create void unlock and if counter raised 3 then to call this void (current JVM should be terminated on success), if success to call

  • create local int variable as counter, and String variable for unlock (there isn't requirement to parse to the integer:-)

  • test for correctness (isSelected) after counter/three JToggleButtons ...., remove all code lines inside, there isn't important to otherwise to 1. reset all JToggleButtons (setSelected(false)) and 2. counter to default value, unlock to "", 4. then to show JOptionPane

  • up to 50 code lines incl. impelmenting a Initial Thread in main class, theoretically you can to use JButtons instead JToggleButtons

whenever I use absolute positioning resizing my JFrame leaves me with some out of place components.

  • add ComponentListener to JFrame,

  • must be delayed by Swing Timer (local variable) with small delay (450-600ms) because this listener firing one event per one pixel, to avoiding (useless) bunch of repainting at runtime

  • call Timer.restart() if resize continued,

  • otherwise Swing Action or ActionListener will fired

  • resize of layer should be wrapped into invokeLater (moving this event to the end of EDT queue)


  • fires the list box listener multiple times ---> hehehe (I'm see that, know about) but why bothering with, is required to use MutableComboBoxModel, not to remove/add XxxListener added to JComboBox at runtime,

  • and using this model properly, with proper notifiers fireXxxXxx, then you can to manage all events that came from or stop that, including the selection in JComboBoxes view :-)

@JamesCherrill please see OPs last post, seems to forgot to tell us that there is JDBC (can't found any words to wrote something cleaver there), then everything is ....??? or maybe isn't ???

  • agree read Oracle tutorial for working code example

  • note (probably typos or fast hands by @JamesCherrill) JCheckBox haven't something with JComboBox, logics is quite/little bit different, for JCheckBox just Boolean value stored in XxxTableModel to represents JCheckBox as Renderer/Editor in JTables view

@JamesCherrill Java8 as standard JDK/JRE???, will be here lots of fun, because as you see curriculum for Java programings homework is based by default on AWT with dinosaurs level, where we are living (own life)

  • you have to override setValueAt with proper notifier

  • change current methods

  • nobody knows how Editor and Renderer is used in your code

  • whats wrong with code example from Oracle tutorial

+1 for Java Naming Conventions

  • and very important details don't to call, never super.paintComponents(gr); but super.paintComponent(gr);

  • paintComponents required little bit more effort and knowledge than simple paintComponent, then is easier to override paintChildren
  • override getPreferredSize for public class GraphicUse extends JPanel, don't forget to add @Overrride annotation too, then all sizing is quite useless and contraproductive, use frame.pack() instead of code line newframe.setSize(250,300);
  • use JSpinner, read Oracle tutorial for working code example instead of String[] Month and String[] Day, otherwise you will able to add funny Date, e.g. 31. february etc...

  • for output to use JTextArea, formatted output from all JTextFields, JSpinners, JComboBoxes (with combine in text from JLabels)


  • this code is about old and refused practicies

  • never use Thread.sleep(int) in Java

  • never use Graphics g2 = panel2.getGraphics(); this method is proper for printing to printer or saving to BufferedImage

  • search here JPanel + paintComponent, delayed by Swing Timer

ActionListener is desingnated to runce only one time, from Mouse or Key Events, issue must be in rest of your code

  • all Layout Managers(customs too), together with JFrame.pack() are calculated on PreferredSize (based on component tree, ZOrder), first is painted last, on top JComponent

  • with some LayoutManagers is possible to resize childs, with some isn't possible (FLowLayout), or settable (GridLayout, SpringLayout, MigLayout)

  • most of LayoutManagers accepts only PreferredSize, relayout (runtime) is done by container.revalidate() & container.repaint()

  • you would need to set initial PreferredSIze (for all LayoutManagers exc AbsoluteLayout) e.g. textArea = new JTextArea(10, 15);

I miss there

  1. override getColumnClass, its very important for JTables view to know data types stored in DefaultTableModel

  2. reset DefaultTableModel to null, use (there are a few another methods, you can to starting with) model.setRowCount(0); before a new rows are added to

  3. create (I assumed that there isn't another column structure, if yes then multiplay this variables) ColumnModel as local variable

  4. (for results from calculations :-) there isn't required table.revalidate(); table.repaint();, be sure that arrays in Java starting with 0 (zero)

  5. close() Statement stmt = null; in finnaly block too, otherwise these Objects stays in JVM memory, can't be GC'ed, increasing JVM used memory

  6. crossposted

i have a problem in logic of swapping in java. That is how to swap no. of buttons with mouse click i am not getting the proper code for that..,please, can anybody there 2 help me out..! thnks

  • whats swapping in java

  • whats hidden in how to swap no. of buttons with mouse click
  1. use JToggleButton

  2. use CardLayout
  • remove panelOne.setSize(300,300);

  • remove super.setSize(300,300); use pack() instead

  • remove all super.Xxx, create an local variable for JFrame

  • JPanels dimension (inside JScrollPane) must be greater than rectangle from JScrollPane (basic property, reason why JScrollPane is there), otherwise JScrollBar isn't visible
  1. use JApplet not Applet (I'd suggest to use JFrame instead)

  2. put there JPanel ant to override paintComponent instad of paint()

  3. 1st. code line should be super.paintComponent(), otherwise all painting will be cumulating

  4. rest is described in Oracle tutorial Performing Custom Painting
  • Please how is possible (probably dirty hack) to create How to Create Translucent and Shaped Windows

    • undecorated container (returns java.awt.IllegalComponentStateException: The frame is displayable.)

    • change Look and Feel for (returns AWT-EventQueue-0" java.awt.IllegalComponentStateException: The frame is decorated)
  • by using code from linked official tutorial


import java.awt.*;
import javax.swing.*;

public class TranslucentWindow extends JFrame {

    private static final long serialVersionUID = 1L;

    public TranslucentWindow() {
        super("Test translucent window");
        setLayout(new FlowLayout());
        add(new JButton("test"));
        add(new JCheckBox("test"));
        add(new JRadioButton("test"));
        add(new JProgressBar(0, 100));
        JPanel panel = new JPanel() {
            public Dimension getPreferredSize() {
                return new Dimension(400, 300);
            private static final long serialVersionUID = 1L;

            protected void paintComponent(Graphics g) {
                g.fillRect(0, 0, getWidth(), getHeight());
        panel.add(new JLabel("Very long textxxxxxxxxxxxxxxxxxxxxx "));

    public static void main(String[] args) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
        } catch (Exception e) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Window w = new TranslucentWindow();
                com.sun.awt.AWTUtilities.setWindowOpacity(w, 0.7f);
  1. model = new DefaultListModel(); should be declared as local variable or separate class

  2. List = new JList( this.observerlink.getlist() );

    a) List is reserved Java word for util.List and awt.List ....change that to myList (Java is CaseSensitive, for more infor to search for Java naming convention)

    b) myList should be local variable

  3. this.scrolllist = new JScrollPane(logList); ... as local variasble

  4. nobody knows whats drawGUI(); probably add JScrollPane with JList to the alreasy visible GUI, revalidate() notify used LayoutManager correctly

  5. don't to create, remove, modify the same JComponents on the runtime, use DeafultListModel, add, remove, modify value there, then all circus about add a new JList is more than contraproductive

  6. for better help sooner post an SSCCE, short, runnable, compilable, just about JFrame with one JList wrapped in JScrollPane

@JamesCherrill :-)


  • aaach now I see we forgot here ...

  • most important issue is that you tried to draw to the Top Level Container,

  • most important issue is that you tried react to KeyEvents (Mouse partially), this events aren't implemented in the API, simple aren't accessible for Top Level Container by default, without ton of (useless) code

  • JFrame isn't proper container for Custom painting

  • put there JComponent / JPanel and to override paintComponent instead of paint

  • override gerPreferredSize for container, otherwise JComponent / JPanel returns zero Dimension, Graphics / Graphics2D by default never returns any size

  • example by one of my pattern


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RacingCars extends JFrame {

    private CarPanel car1;
    private CarPanel car2;

    public RacingCars() {//Constructor
        setLayout(new GridLayout(2, 1));
        car1 = new CarPanel('w', Color.RED);
        car2 = new CarPanel('k', Color.blue);
        this.add(car1, BorderLayout.NORTH);
        this.add(car2, BorderLayout.SOUTH);
        this.addKeyListener(new MyKeyListener());

    class MyKeyListener extends KeyAdapter {

        public void keyPressed(KeyEvent e) {
            if (e.getKeyChar() == 'w') {
            if (e.getKeyChar() == 'k') {

    public static void main(String[] args) {
        //Create the frame on the event dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                RacingCars rc = new RacingCars();

class CarPanel extends JPanel {

    private char forwardKey = 'w';
    private boolean reachedTarget = false;
    private Color color = Color.blue;
    private int x = 10;
    private int y = 10;
    private int panelWidth;
    private int ...
  • all discusion about KeyListner is wrong, caused a few another side effects from usage of wrong Listener

  • there no reason call for repaint(), why repeating, supply methods implemented in API, all those notifiers are implemented and correctly

  • not, never to use KeyListener for Swing JComponents, this Listener is designated for AWT Components,

  • have to use hight possible abstraction for Swing JComponents, use KeyBindings instead of Keylistener

  • output from KeyBindings will be Swing Action, rather then ActionListener directly

  • KeyBindins are scallable, shareable, settable (same for Swing Action) for Focus in the window, then there isn't required to hunting for Focus or programatically to set setFocusable,

  • simple example

harinath_2007 wrote Whenever the text in the textarea fills up completely , i want the scrollbar to scroll down.

there are two ways:

1st. way

JTextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();

2nd. way

  • get the JScrollBar from JScrollPane as local variable,
  • add DocumentListener to JTextArea
  • from proper Document event to call max value for JScrollbar


AFAIK not possible, without JNI/JNA, otherwise Font, Color, MessageType is based on resources came from Native OS, in the case that you'll to change theme in OS, then will be changed these properties too, accesible frome Win32, Net, C++, e.i.

  • upvotes works, I'll try to edit this post :-)

  • edited, edits & upvotes works from my account here

have to add PrintRequestAttributeSet before printing to Printer

PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
Table_Stud.print(JTable.PrintMode.FIT_WIDTH, header, footer, false, set, false);

commented: highly appreciated.. +3