Change the textfield location of a JSpinner - java

I'd like to custom a little bit the basic JSpinner of swing java API.
Basically, I want to move the textfield component initially located on the left of the arrow buttons. Instead, the texfield would be lcoated between the two arrows of the spinner, so that there's one arrow on top of the textfield and one arrow below the texfield.
But I don't know how to proceed...
Anyone would have an idea?

You might be able to override the setLayout(LayoutManager) method of JSpinner to use a custom LayoutManager.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpinnerLayoutTest {
public JComponent makeUI() {
SpinnerNumberModel m = new SpinnerNumberModel(10, 0, 1000, 1);
JSpinner spinner = new JSpinner(m) {
#Override public void setLayout(LayoutManager mgr) {
super.setLayout(new SpinnerLayout());
}
};
JPanel p = new JPanel(new BorderLayout(5,5));
p.add(new JSpinner(m), BorderLayout.NORTH);
p.add(spinner, BorderLayout.SOUTH);
p.setBorder(BorderFactory.createEmptyBorder(16,16,16,16));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new SpinnerLayoutTest().makeUI());
f.setSize(320, 160);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class SpinnerLayout extends BorderLayout {
#Override public void addLayoutComponent(Component comp, Object constraints) {
if("Editor".equals(constraints)) {
constraints = "Center";
} else if("Next".equals(constraints)) {
constraints = "North";
} else if("Previous".equals(constraints)) {
constraints = "South";
}
super.addLayoutComponent(comp, constraints);
}
}

You could make an JPanel and put a JTextField and the JButtons inside it. That's was soulution, when I had the same problem.
EDIT:
Arrowbuttons can you create with:
new javax.swing.plaf.basic.BasicArrowButton(SwingConstants.NORTH);
Where SwingConstants.NORTH says that the arrow in the button is pointing upwards

Related

Responsive JFrame without Layout Manager

I am trying to do have two button in JFrame, and I call the setBounds method of them for setting the positions and size of them and also I passed null to setLayout1 because I want to usesetBounds` method of component.
Now I want to do something with my code that whenever I resize the frame buttons decoration will change in a suitable form like below pictures:
I know it is possible to use create an object from JPanel class and add buttons to it and at the end add created panel object to frame, but I am not allowed to it right now because of some reason (specified by professor).
Is there any way or do you have any suggestion?
My code is like this:
public class Responsive
{
public static void main(String[] args)
{
JFrame jFrame = new JFrame("Responsive JFrame");
jFrame.setLayout(null);
jFrame.setBounds(0,0,400,300);
JButton jButton1 = new JButton("button 1");
JButton jButton2 = new JButton("button 2");
jButton1.setBounds(50,50,100,100);
jButton2.setBounds(150,50,100,100);
jFrame.add(jButton1);
jFrame.add(jButton2);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
}
A FlowLayout with no horizontal spacing, some vertical spacing and large borders could achieve that easily. A null layout manager is never the answer to a 'responsive' robust GUI.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ResponsiveGUI {
private JComponent ui = null;
ResponsiveGUI() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 8));
ui.setBorder(new EmptyBorder(10,40,10,40));
for (int i=1; i<3; i++) {
ui.add(getBigButton(i));
}
}
public JComponent getUI() {
return ui;
}
private final JButton getBigButton(int number) {
JButton b = new JButton("Button " + number);
int pad = 20;
b.setMargin(new Insets(pad, pad, pad, pad));
return b;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ResponsiveGUI o = new ResponsiveGUI();
JFrame f = new JFrame("Responsive GUI");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
You could try to use:
jFrame.addComponentListener(new ComponentListener() {
// this method invokes each time you resize the frame
public void componentResized(ComponentEvent e) {
// your calculations on buttons
}
});

What is the proper way to swap out an existing JPanel in a JFrame with another?

I'm building a program that requires swapping out the current, visible JPanel with another. Unfortunately there seems to be multiple to go about this and all of my attempts have ended in failure. I can successfully get the first JPanel to appear in my JFrame, but swapping JPanels results in a blank JFrame.
My Main JFrame:
public class ShellFrame {
static CardLayout cl = new CardLayout(); //handles panel switching
static JFrame frame; //init swing on EDT
static MainMenu mm;
static Panel2 p2;
static Panel3 p3;
public static void main(String[] args) {
initFrame();
}
public static void initFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(3);
frame.setLayout(cl);
mm = new MainMenu();
pp = new PlacementPanel();
//first panel added to frame will always show first
frame.add(mm, "MainMenu");
frame.pack(); //sizes frame to fit the panel being shown
frame.setVisible(true);
}
});
}
public static void switchPanel(String name) {
cl.show(frame.getContentPane(), name);
frame.pack();
}
public static void updatePanel2(/* args */) {
frame.removeAll();
p2 = new Panel2(/* args */);
frame.add(pp, "PlacementPanel");
frame.pack();
frame.validate();
frame.repaint();
}
I'm trying to use updatePanel2 to swap out the existing panel with a new Panel2 but It doesn't seem to be working. Panel2 works fine on it's own but trying to use it in conjunction with my program simply yields a blank window. Any help would be greatly appreciated!
that requires swapping out the current, visible JPanel with another
Have a look at CardLayout for a complete example of how to do it properly.
I have a Swing app which 'swaps' Panels when the user press the 'SPACE' key, showing a live plot of a running simulation. What i did goes like this:
public class MainPanel extends JPanel implements Runnable {
// Called when the JPanel is added to the JFrame
public void addNotify() {
super.addNotify();
animator = new ScheduledThreadPoolExecutor(1);
animator.scheduleAtFixedRate(this, 0, 1000L/60L, TimeUnit.MILLISECONDS);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (spacePressed)
plot.render(g);
else
simulation.render(g);
}
public void run() {
simulation.update();
repaint();
}
}
public class PlotView {
public void render(Graphics g) {
//draw the plot here
}
}
public class SimulationView {
public void render(Graphics g) {
//draw simulation here
}
}
This works very well for my 'show live plot' problem. And there's also the CardLayout approach, which you may turn into a new separate question if you having trouble. Good luck!
You should do .setVisible(false); to the panel which you want to be replaced.
Here is a working example, it switches the panels when you press "ENTER";
If you copy this in an IDE, automatically get the imports (shift+o in Eclipse);
public class MyFrame extends JFrame implements KeyListener {
private JButton button = new JButton("Change Panels");
private JPanel panelOnFrame = new JPanel();
private JPanel panel1 = new JPanel();
public MyFrame() {
// adding labels to panels, to distinguish them
panelOnFrame.add(new JLabel("panel on frame"));
panel1.add(new JLabel("panel 1"));
setSize(new Dimension(250,250));
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(button);
add(panelOnFrame);
setVisible(true);
addKeyListener(this);
addKeyListener(this);
setFocusable(true);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
#Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_ENTER){
//+-------------here is the replacement:
panelOnFrame.setVisible(false);
this.add(panel1);
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}

Giving a JPanel priority focus

I have a JPanel that is using a KeyListener as the content pane as the window; however, there are buttons and text fields in a grid layout on top of the JPanel.
How do I prioritize the focus of the JPanel that it retains focus after editing text or clicking the buttons so I can read the key input?
You just need to add a FocusListener on the focusLost event and then request focus back again. Something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPanelFocus {
public static void main(String... argv) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("FocusTest");
JButton b = new JButton("Button");
final JPanel p = new JPanel();
p.add(b);
// Here is the KeyListener installed on our JPanel
p.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ev) {
System.out.println(ev.getKeyChar());
}
});
// This is the bit that does the magic - make sure
// that our JPanel is always focussed
p.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent ev) {
p.requestFocus();
}
});
f.getContentPane().add(p);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// Make sure JPanel starts with the focus
p.requestFocus();
}
});
}
}
This won't work if you have fields that need to keep the focus though (you mentioned an editable text field). When should key events go to the text field and when should they go to the JPanel?
As an alternative, you could also just make the child components non-focusable.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel implements KeyListener {
public MyPanel() {
this.setFocusable(true);
this.addKeyListener(this);
// for each component
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Item1");
this.add(comboBox);
// this is what keeps each child from intercepting KeyEvents
comboBox.setFocusable(false);
}
public void keyPressed(KeyEvent e) { ... }
public void keyTyped(KeyEvent e) { ... }
public void keyReleased(KeyEvent e) { ... }
public static void main(String[] args) {
// create a frame
JFrame frame = new JFrame();
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add MyPanel to frame
MyPanel panel = new MyPanel();
frame.add(panel);
frame.setVisible(true);
}
}

Tabed pane with a label on top

I need to add a JLabel/JPanel as shown in the image. When resizing the frame both the tabbed pane and the Label/panel should be resided. The label and the panel inside the Tabbed Pane are independent. How can I do that?
Here is a quick example to use JLayer(as suggested by mKorbel):
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TopRightCornerLabelLayerUITest {
public static JComponent makeUI() {
JTabbedPane tab = new JTabbedPane();
tab.addTab("New tab1", new JLabel("1"));
tab.addTab("New Tab2", new JLabel("2"));
JPanel p = new JPanel(new BorderLayout());
p.add(new JLayer<JComponent>(tab, new TopRightCornerLabelLayerUI()));
return p;
}
private static void createAndShowUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowUI();
}
});
}
}
class TopRightCornerLabelLayerUI extends LayerUI<JComponent> {
private JLabel l = new JLabel("A Label at right corner");
private JPanel rubberStamp = new JPanel();
#Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Dimension d = l.getPreferredSize();
int x = c.getWidth() - d.width - 5;
SwingUtilities.paintComponent(g, l, rubberStamp, x, 2, d.width, d.height);
}
}
I need to add a JLabel/JPanel as shown in the image. When resizing the
frame both the tabbed pane and the Label/panel should be resided. The
label and the panel inside the Tabbed Pane are independent.. If any
one have the solution, please help me.
You can use:
JLayer (Java7) based on JXLayer(Java6)
GlassPane, for example
I'd use JLayer if is possible (requires Java7).

Adding jinternalframe class to jdesktoppane using other jinternalframe class

I'm creating a very simple program.
I have created this classes :
MainJframeClass, JDesktopPaneClass, JinternalFrameClass1 and JinternalFrameClass2.
what ive done is that i instantiated my jdesktoppaneclass and named it desktoppane1 and i added it to the MainJframeclass. i have also instantiated the 2 jinternalframes and named it internal1 and internal2. Now, i have button in mainjframeclass that when i press, i add the internal1 to desktoppane1. what my problem now is how to add the internal2 to desktoppane1 using a button placed somewhere in internal1. i know that why could i just add another button to desktoppane1 and add the internal2. but i have done it already, i just want to solve this problem. if you can help me please. sorry for my english by the way.
It's simply a matter of references. The code that adds something to the JDesktopPane must have a reference to it, and so you will need to pass that reference into the class that needs it say via either a constructor parameter or a method parameter.
Edit 1
For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class ReferenceExample extends JPanel {
private JDesktopPane desktop = new JDesktopPane();
private Random random = new Random();
public ReferenceExample() {
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addInternalFrame();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addInternalFrameBtn);
setPreferredSize(new Dimension(600, 450));
setLayout(new BorderLayout());
add(new JScrollPane(desktop), BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
public void addInternalFrame() {
MyInternalFrame intFrame = new MyInternalFrame(ReferenceExample.this);
int x = random.nextInt(getWidth() - intFrame.getPreferredSize().width);
int y = random.nextInt(getHeight() - intFrame.getPreferredSize().height);
intFrame.setLocation(x, y);
desktop.add(intFrame);
intFrame.setVisible(true);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Reference Eg");
frame.getContentPane().add(new ReferenceExample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyInternalFrame extends JInternalFrame {
// pass in the reference in the constructor
public MyInternalFrame(final ReferenceExample refEg) {
setPreferredSize(new Dimension(200, 200));
setClosable(true);
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// use the reference here
refEg.addInternalFrame();
}
});
JPanel panel = new JPanel();
panel.add(addInternalFrameBtn);
getContentPane().add(panel);
pack();
}
}
how to add the internal2 to desktoppane1 using a button placed somewhere in internal1.
In the ActionListener added to your button you can use code like the following to get a reference to the desktop pane:
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)event.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame frame = new JInternalFrame(...);
desktop.add( frame );
}

Categories