EzDevInfo.com

swing interview questions

Top swing frequently asked interview questions

The Use of Multiple JFrames, Good/Bad Practice? [closed]

I'm developing an application which displays images, and plays sounds from a database. I'm trying to decide, whether to use a separate JFrame to add Images to the Database from the GUI. I'm just wondering whether it is good practice to use multiple JFrames?


Source: (StackOverflow)

How to add hyperlink in JLabel

Which is the best way to add a hyperlink in jLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?


Source: (StackOverflow)

Advertisements

How to bring a window to the front?

We have a Java-application that needs to be brought to the foreground when a telecontrol mechanism activates something in the application.

In order to get this we have realised in the called method of the Class which represents the Frame of our application (extension of a JFrame) following implementation:

setVisible(true);
toFront();

Under Windows XP this works the first time it is called, on the second time only the tab in the taskbar flashes, the frame doesn't come to the front anymore. Same goes for Win2k. On Vista it seems to work fine.

Anyone ideas?


Source: (StackOverflow)

How to best position Swing GUIs?

In another thread I stated that I liked to center my GUIs by doing something like this:

JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HexagonGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

But Andrew Thompson had a different opinion, to instead call

frame.pack();
frame.setLocationByPlatform(true);

and inquiring minds want to know why?


Source: (StackOverflow)

Detect enter press in JTextField

Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.


Source: (StackOverflow)

Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Several times I've been criticized for having suggested the use of the following methods:

  1. setPreferredSize
  2. setMinimumSize
  3. setMaximumSize

on Swing components. I don't see any alternative to their use when I want to define proportions between displayed components. I have been told this:

With layouts the answer is always the same: use a suitable LayoutManager

I have searched the web a little bit, but I haven't found any comprehensive analysis of the subject. So I have the following questions:

  1. Should I completely avoid the use of those methods?
  2. The methods have been defined for a reason. So when should I use them? In which context? For what purposes?
  3. What exactly are the negative consequences of using those methods? (I can only think adding portability between systems with different screen resolution).
  4. I don't think any LayoutManager can exactly satisfy all desired layout needs. Do I really need to implement a new LayoutManager for every little variation on my layout ?
  5. If the answer to 4 is "yes", won't this lead to a proliferation of LayoutManager classes which will become difficult to maintain?
  6. In a situation where I need to define proportions between children of a Component (eg, child1 should use 10% of space, child2 40% ,child3 50%), is it possible to achieve that without implementing a custom LayoutManager?

I hope to have been clear.


Source: (StackOverflow)

How to add an image to a JPanel?

I have a JPanel to which I'd like to add JPEG and PNG images that I generate on the fly.

All the examples I've seen so far in the Swing Tutorials, specially in the Swing examples use ImageIcons.

I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.

  1. Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?
  2. What's the usual way of doing it?
  3. How to add an image to a JPanel without using the ImageIcon class?

Edit: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...


Source: (StackOverflow)

Java Swing revalidate() vs repaint()

I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling removeAll(), then adding my new content, then calling revalidate().

However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to repaint() in addition to revalidate(), it works as expected.

I'm sure on other occasions I've experienced that just calling revalidate() is enough.

So basically my question is - should I need to call both functions and if not, when should I call each of them?


Source: (StackOverflow)

GUI not working after rewriting to MVC

I'm practicing MVC style programming. I have a Mastermind game in a single file, working fine (maybe apart of the fact that "Check" button is invisible at start).

http://paste.pocoo.org/show/226726/

But when I've rewritten it to model, view, controller files - and when I click on empty Pin (that should be updated, and repainted with new color) - noting happens. Can anybody see any problems here ? I've tried placing repaint() in different places, but it simply does not work at all :/

Main :

public class Main { 
    public static void main(String[] args){
        Model model = new Model();
        View view = new View("Mastermind", 400, 590, model);
        Controller controller = new Controller(model, view); 
        view.setVisible(true);
    }
}

Model :

import java.util.Random;

public class Model{
    static final int
    LINE = 5,
    SCORE = 10, OPTIONS = 20;
    Pin pins[][] = new Pin[21][LINE];
    int combination[] = new int[LINE];
    int curPin = 0;
    int turn = 1;
    Random generator = new Random();
    int repaintPin;
    boolean pinsRepaint=false;
    int pinsToRepaint;
    boolean isUpdate = true, isPlaying = true, isRowFull = false;
    static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516};

    public Model(){

        for ( int i=0; i < SCORE; i++ ){
            for ( int j = 0; j < LINE; j++ ){
                pins[i][j] = new Pin(20,0);
                pins[i][j].setPosition(j*50+30,510-i*50);
                pins[i+SCORE][j] = new Pin(8,0);
                pins[i+SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50);
            }
        }
        for ( int i=0; i < LINE; i++ ){
            pins[OPTIONS][i] = new Pin( 20, i+2 );
            pins[OPTIONS][i].setPosition( 370,i * 50 + 56);
        }

    }

    void fillHole(int color) {
        pins[turn-1][curPin].setColor(color+1);
        pinsRepaint = true;
        pinsToRepaint = turn;
        curPin = (curPin+1) % LINE;
        if (curPin == 0){
            isRowFull = true;
        }
        pinsRepaint = false;
        pinsToRepaint = 0;
    }

    void check() {
        int junkPins[] = new int[LINE], junkCode[] = new int[LINE];
        int pinCount = 0, pico = 0;

        for ( int i = 0; i < LINE; i++ ) {
            junkPins[i] = pins[turn-1][i].getColor();
            junkCode[i] = combination[i];
        }
        for ( int i = 0; i < LINE; i++ ){
            if (junkPins[i]==junkCode[i]) {
                pins[turn+SCORE][pinCount].setColor(1);
                pinCount++;
                pico++;
                junkPins[i] = 98;
                junkCode[i] = 99;
            }
        }
        for ( int i = 0; i < LINE; i++ ){
            for ( int j = 0; j < LINE; j++ )
                if (junkPins[i]==junkCode[j]) {
                    pins[turn+SCORE][pinCount].setColor(2);
                    pinCount++;
                    junkPins[i] = 98;
                    junkCode[j] = 99;
                    j = LINE;
            }
        }
        pinsRepaint = true;
        pinsToRepaint = turn + SCORE;
        pinsRepaint = false;
        pinsToRepaint=0;

        if ( pico == LINE ){
            isPlaying = false;
        }
        else if ( turn >= 10 ){
                isPlaying = false;
        }
        else{
            curPin = 0;
            isRowFull = false;
            turn++;
        }
    }

    void combination() {
        for ( int i = 0; i < LINE; i++ ){
          combination[i] = generator.nextInt(6) + 1;
        }
    }
}

class Pin{
    private int color, X, Y, radius;

    public Pin(){
        X = 0; Y = 0; radius = 0; color = 0;
    }

    public Pin( int r,int c ){
        X = 0; Y = 0; radius = r; color = c;
    }

    public int getX(){
        return X;
    }

    public int getY(){
        return Y;
    }

    public int getRadius(){
        return radius;
    }

    public void setRadius(int r){
        radius = r;
    }

    public void setPosition( int x,int y ){
        this.X = x ;
        this.Y = y ;
    }
    public void setColor( int c ){
        color = c;
    }
    public int getColor() {
        return color;
    }
}

View:

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

public class View extends Frame{  
    Model model;
    JButton checkAnswer;
    private JPanel button;
    private static final Color COLORS[] = {Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)};

    public View(String name, int w, int h, Model m){
        model = m;
        setTitle( name );
        setSize( w,h );
        setResizable( false );
        this.setLayout(new BorderLayout());

        button = new JPanel();
        button.setSize( new Dimension(400, 100));
        button.setVisible(true);
        checkAnswer = new JButton("Check");
        checkAnswer.setSize( new Dimension(200, 30));
        button.add( checkAnswer );
        this.add( button, BorderLayout.SOUTH);
        button.setVisible(true);
    }

    @Override
    public void paint( Graphics g ) {
        g.setColor( new Color(238, 238, 238));
        g.fillRect( 0,0,400,590);

        for ( int i=0; i < model.pins.length; i++ ) {
            paintPins(model.pins[i][0],g);
            paintPins(model.pins[i][1],g);
            paintPins(model.pins[i][2],g);
            paintPins(model.pins[i][3],g);
            paintPins(model.pins[i][4],g);
        }
    }

    @Override
    public void update( Graphics g ) {
        if ( model.isUpdate ) {
            paint(g);
        }
        else {
            model.isUpdate = true;
            paintPins(model.pins[model.repaintPin-1][0],g);
            paintPins(model.pins[model.repaintPin-1][1],g);
            paintPins(model.pins[model.repaintPin-1][2],g);
            paintPins(model.pins[model.repaintPin-1][3],g);
            paintPins(model.pins[model.repaintPin-1][4],g);
        }
    }

    void repaintPins( int pin ) {
        model.repaintPin = pin;
        model.isUpdate = false;
        repaint();
    }

    public void paintPins(Pin p, Graphics g ){
        int X = p.getX();
        int Y = p.getY();
        int color = p.getColor();
        int radius = p.getRadius();
        int x = X-radius;
        int y = Y-radius;

        if (color > 0){
            g.setColor( COLORS[color]);
            g.fillOval( x,y,2*radius,2*radius );
        }
        else{
            g.setColor( new Color(238, 238, 238) );
            g.drawOval( x,y,2*radius-1,2*radius-1 );
        }
        g.setColor( Color.black );
        g.drawOval( x,y,2*radius,2*radius );
    }
}

Controller:

import java.awt.*;
import java.awt.event.*;

public class Controller implements MouseListener, ActionListener { 
    private Model model;
    private View view;

    public Controller(Model m, View v){ 
        model = m;
        view = v;

        view.addWindowListener( new WindowAdapter(){
            public void windowClosing(WindowEvent e){
            System.exit(0);
        } });
        view.addMouseListener(this);
        view.checkAnswer.addActionListener(this);
        model.combination();
    }

    public void actionPerformed( ActionEvent e ) {
        if(e.getSource() == view.checkAnswer){
            if(model.isRowFull){
                model.check();
            }
        }
    }

    public void mousePressed(MouseEvent e) {
        Point mouse = new Point();

        mouse = e.getPoint();
        if (model.isPlaying){
            if (mouse.x > 350) {
                int button = 1 + (int)((mouse.y - 32) / 50);
                if ((button >= 1) && (button <= 5)){
                    model.fillHole(button);
                    if(model.pinsRepaint){
                        view.repaintPins( model.pinsToRepaint );
                    }
                }
            }
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e)  {}
}

Source: (StackOverflow)

JComboBox Selection Change Listener?

I'm trying to get an event to fire whenever a choice is made from a JComboBox.

The problem I'm having is that there is no obvious addSelectionListener() method.

I've tried to use actionPerformed() but it never fires.

Short of overriding the model for the JComboBox I'm out of ideas.

How do I get notified of a selection change on a JComboBox?

Edit: I have to apologize it turns out I was using a misbehaving subclass of JComboBox, but I'll leave the question up since your answer is good. Commence the vote down. :)


Source: (StackOverflow)

What is the difference between Swing and AWT?

Can someone please explain me what's the difference between Swing and AWT?

Are there any cases where AWT is more useful/advised to use than swing or vice-versa?


Source: (StackOverflow)

Java Look and Feel (L&F) [closed]

I am developing a desktop application with Java Swing for my personal use.I am in need of some beautiful Look and Feel for my application. How can I do it using Java or a 3rd party API?


Source: (StackOverflow)

Value Change Listener to JTextField

I want the message box to appear immediately after the user changes the value in the textfield. Currently, I need to hit the enter key to get the message box to pop out. Is there anything wrong with my code?

textField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {

        if (Integer.parseInt(textField.getText())<=0){
            JOptionPane.showMessageDialog(null,
                    "Error: Please enter number bigger than 0", "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }       
    }
}

Any help would be appreciated!


Source: (StackOverflow)

How to make a JTable non-editable

How to make a JTable non-editable? I don't want my users to be able to edit the values in cells by double-clicking them.

Any help would be greatly appreciated.

Thanks.


Source: (StackOverflow)

"Always on Top" Windows with Java

In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it?


Source: (StackOverflow)