5
\$\begingroup\$

I am writing a control panel with Sliders but I think my code is messy and cumbersome, what can I do to improve it?

public class Input_Window extends JFrame {
    JSlider myslideA,myslideB,myslideC,myslideD;

    Input_Window(){
        System.out.println("* Control Window");
        setBackground(Color.GRAY);  
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Controls");
        setSize(200,400);
        setLocation(1200,250);
        setLayout(new FlowLayout());
        myslideA=slider(0,10,3,1,true,true);
        add(myslideA);
        myslideB=slider(0,10,3,1,true,true);
        add(myslideB);
        myslideC=slider(0,10,3,1,true,true);
        add(myslideC);
        myslideD=slider(0,10,3,1,true,true);
        add(myslideD);
        setVisible(true);  
        setFocusable(true); 
        requestFocus();
    }

    public final JSlider slider(int min, int max, int def, int maj, boolean ticks, boolean labels){

        JSlider myslide=new JSlider(JSlider.HORIZONTAL,min,max,def);
        myslide.setMajorTickSpacing(maj);
        myslide.setPaintTicks(ticks);
        myslide.setPaintLabels(labels);
        return (myslide);
    }

}
\$\endgroup\$
4
\$\begingroup\$
  1. Naming:
    Your class is named Input_Window which violates standard Java naming conventions of PascalCase (without underscores).

  2. Formatting:
    An equal sign should be surrounded by spaces:

    myslideA = slider(0,10,3,1,true,true);
    //and so on...
    
  3. Visibilities:

    • Your JSliders should most probably be private. nobody aside from your InputWindow should have to know about them. If there's someone out there who wants to know about GUI except the GUI you're doing things wrong ...
    • slider should also be private. If somebody else uses it, extract it to a utility-class. Hide the information where ever you can. If you don't things may happen with your stuff when you're not watching.
  4. Responsibilities:
    Your constructor shouldn't request focus and set the window to visible himself. That's things that should be done in calling code. You don't expect a JFrame to show up on instantiation either, right?

\$\endgroup\$
1
  • \$\begingroup\$ Agreed on #4. If it were normal for JFrames to make themselves visible and request focus, then the JFrame constructor would have done so. \$\endgroup\$ Dec 15 '14 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.