Java Window Event - Maximize. How to hardcode? - java

I have a JDesktopPane and a JInternalFrame. I'd like the JInternalFrame to automatically maximize after I make it. How can I hardcode the "maximize window" event?

Use JInternalFrame.setMaximum(true) after you create your frame.
Here is how you can maximize your frame:
JInternalFrame frame = ...
frame..setMaximum(true); // Maximize this window to fill up the whole desktop area

Setting the method setMaximum(boolean b) of JInternalFrame to "true" , will maximize it.
eg:
JInternalFrame.setMaximum(true)

already suggested above: JInternalFrame#setMaximum(boolean)
Another option: DesktopManager#maximizeFrame(JInternalFrame)
a bit different behavior when JDesktopPane resized.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JInternalFrameMaximumTest {
public JComponent makeUI() {
final JDesktopPane desktop = new JDesktopPane();
Action a1 = new AbstractAction("JInternalFrame#setMaximum") {
#Override public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("#",true,true,true,true);
desktop.add(f);
f.setVisible(true);
try {
f.setMaximum(true);
} catch(java.beans.PropertyVetoException ex) {
ex.printStackTrace();
}
}
};
Action a2 = new AbstractAction("DesktopManager#maximizeFrame(f)") {
#Override public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("#",true,true,true,true);
desktop.add(f);
f.setVisible(true);
desktop.getDesktopManager().maximizeFrame(f);
}
};
JToolBar toolbar = new JToolBar("toolbar");
toolbar.add(new JButton(a1));
toolbar.add(new JButton(a2));
JPanel p = new JPanel(new BorderLayout());
p.add(desktop);
p.add(toolbar, BorderLayout.NORTH);
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 JInternalFrameMaximumTest().makeUI());
f.setSize(640, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Related

JLabel.setVisible while running

I have the main class that instantiates a GridBagLayout with a JLabel visbility set to false.
I would like to set the label visible when the program is running, I have tried this but it won't work. It will just display the default layout.
Main class:
gui = new gui();
gui.display();
gui.label.setVisible(true);
Gridbag layout class:
public JFrame frame;
public JLabel label1;
/**
* Launch the application.
*/
public static void display(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gridLayout window = new gridLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
* Create the application.
*/
public gridLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
#SuppressWarnings("static-access")
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
frame.getContentPane().setLayout(gridBagLayout);
}
label1 = new JLabel(new ImageIcon("hi"));
GridBagConstraints gbc_label1 = new GridBagConstraints();
gbc_label1.insets = new Insets(0, 0, 5, 5);
gbc_label1.gridx = 1;
gbc_label1.gridy = 1;
label1.setVisible(false);
frame.getContentPane().add(label1, gbc_label1);
You want to display a label while a programme is running, right? This has nothing to do with the layout manager.
I give you an example where the label is visible as long as a dialog (representing your task/programme) is displayed; and I hope you can adopt it to your needs. Possibly you have to put the programme/task in an own thread.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Y extends JFrame {
public static final long serialVersionUID = 100L;
public Y() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 240);
JLabel lb= new JLabel("Programme is running ...");
lb.setVisible(false);
add(lb, BorderLayout.CENTER);
JButton b= new JButton("Launch programme (dialog)");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lb.setVisible(true);
JDialog dlg= new JDialog(Y.this, "The dialog", true);
dlg.setSize(100, 100);
dlg.setVisible(true);
lb.setVisible(false);
}
});
add(b, BorderLayout.SOUTH);
setVisible(true);
}
static public void main(String args[]) {
EventQueue.invokeLater(Y::new);
}
}

Swing Button Invisible until actionPerformed

Is it possible to create a button that won't be seen until the user clicks another button?
My goal is for the button to be invisible by default rather than when its clicked on. Then become visible when another action is performed. The code below is my original attempt at creating this.
public void but_roll1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (!bal_but.isEnabled() && !gamble_but.isEnabled()) {
but_roll1.setVisible(true);
but_roll1.setEnabled(true);
d1 = diceRoll();
die1_display.setText(String.valueOf(d1));
but_roll1.setEnabled(false);
} else {
but_roll1.setVisible(false);
}
}
Two better strategies:
Put the button in a CardLayout with a second blank panel till needed.
Make the button disabled until the first button is clicked.
I prefer the 2nd as the 'path of least surprise' for the user. YMMV.
Initial view
View after 'effect' button actioned
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonNotUsableTillAction {
private JComponent ui = null;
ButtonNotUsableTillAction() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(1, 0, 4, 4));
ui.setBorder(new EmptyBorder(4,4,4,4));
// first demo, using card layout
JPanel cardDemoPanel = new JPanel(new GridLayout(1, 0, 2, 2));
cardDemoPanel.setBorder(new TitledBorder("Card Layout"));
ui.add(cardDemoPanel);
JButton actionCardButton = new JButton("Action");
cardDemoPanel.add(actionCardButton);
CardLayout cardLayout = new CardLayout();
JPanel cardLayoutPanel = new JPanel(cardLayout);
cardDemoPanel.add(cardLayoutPanel);
cardLayoutPanel.add(new JPanel(), "panel");
cardLayoutPanel.add(new JButton("Effect"), "button");
cardLayout.show(cardLayoutPanel, "panel");
ActionListener flipCardListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardLayoutPanel, "button");
}
};
actionCardButton.addActionListener(flipCardListener);
// first demo, using disabled / enabled
JPanel enabledDemoPanel = new JPanel(new GridLayout(1, 0, 2, 2));
enabledDemoPanel.setBorder(new TitledBorder("Enabled"));
ui.add(enabledDemoPanel);
JButton actionEnabledButton = new JButton("Action");
enabledDemoPanel.add(actionEnabledButton);
JButton effectButton = new JButton("Effect");
enabledDemoPanel.add(effectButton);
effectButton.setEnabled(false);
ActionListener enableComponentListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
effectButton.setEnabled(true);
}
};
actionEnabledButton.addActionListener(enableComponentListener);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ButtonNotUsableTillAction o = new ButtonNotUsableTillAction();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
As #markspace mentioned, you need to revalidate the button's container after setting the button visible:
but_roll1.getParent().revalidate();

How to center component vertically in JPanel which useFlowLayout

I have a certain panel which contains a random number of items. This panel is added to the EAST of a JPanel which use BorderLayout.
I'd like to have them vertically centered.
How do i achieve this?
here is a code you can run
public class MainFrame {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new AlignDemo());
}
}
class AlignDemo implements Runnable {
#Override
public void run(){
try {
JFrame mainWindow = new JFrame();
mainWindow.getContentPane().add(initPanel());
mainWindow.pack();
mainWindow.setVisible(true);
} catch (Throwable th) {
JOptionPane.showMessageDialog(null,null,"General Error", JOptionPane.ERROR_MESSAGE);
}
}
private JPanel initPanel() {
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
layout.setHgap(15);
JPanel myContent = new JPanel();
myContent.setPreferredSize(new Dimension(400,200));
myContent.setBorder(BorderFactory.createLineBorder(Color.blue));
JButton button1 = new JButton("I'm a button");
JButton button2 = new JButton("I'm a button");
JButton button3 = new JButton("I'm a button");
myContent.add(button1,Component.CENTER_ALIGNMENT);
myContent.add(button2,Component.CENTER_ALIGNMENT);
myContent.add(button3,Component.CENTER_ALIGNMENT);
return myContent;
}
}
It can easily be achieved by combining layouts. A JPanel with FlowLayout (controls) to position the buttons relative to one another, placed as a single component into a JPanel with a GridBagLayout (ui).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class CenteredButtons2 {
private JComponent ui = null;
CenteredButtons2() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout()); // to center a single component
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel controls = new JPanel(new FlowLayout());
for (int ii=1; ii<4; ii++) {
controls.add(new JButton("Button " + ii));
}
controls.setBorder(new EmptyBorder(50, 90, 50, 90));
ui.add(controls);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CenteredButtons2 o = new CenteredButtons2();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Create a shortcut in JFrame

public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
public class myclass extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
System.out.println("Key \"Delete\" Pressed");
}
}
}
}
But, when i press delete button, not see the "Key \"Delete\" Pressed" message!
JFrame (all Top-Level Containers) by default never to react to KeyEvents, have to use this Listener for JComponent they are to consume Focus, or is possible to flag it with setFocusable()
don't to use low_level KeyListener for Swing JComponents, if is possible then to use hight level abstraction, to use KeyBindings instead
JRootPane + KeyBindings(As #mKorbel has already said)
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
Also check out: JMenuItem#setAccelerator(...)
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
public static JMenuBar makeMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Test");
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
menu.add(item);
bar.add(menu);
return bar;
}
public static Action action = new AbstractAction("UserPage?") {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("UserPage Action");
}
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setJMenuBar(makeMenuBar());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Adding JApplet into JFrame

I am trying to view a JApplet within a JFrame.
Class: Paint
public void paint(Graphics g) {
g.drawString("hi", 50, 50);
}
public static void main(String args[]) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(methodThatReturnsJMenuBar());
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
JApplet applet = new Paint();
panel.add(applet, BorderLayout.CENTER);
applet.init();
frame.pack();
frame.setVisible(true);
}
The applet shows up in the Window, but there is no background (it's transparent), and when I click on the Menu, the list is covered. How do I make it so that the Menu list isn't covered, and there is a background?
Edit: When I draw a white rectangle, it fixes the background problem, but the Menu list is still covered.
I would gear my GUI creation towards making a JPanel and then use the JPanel as I desire, either in an JApplet or a JFrame. For e.g.,
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(400, 300);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hi", 50, 50);
}
#Override
public Dimension getPreferredSize() {
return PREF_SIZE;
}
public JMenuBar methodThatReturnsJMenuBar() {
JMenu menu = new JMenu("Menu");
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
}
Then to use in an applet:
import javax.swing.JApplet;
public class MyApplet extends JApplet {
public void init() {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI() {
getContentPane().add(new MyPanel());
}
}
Or in a JFrame:
import javax.swing.JFrame;
public class MyStandAlone {
private static void createAndShowUI() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("MyPanel");
frame.getContentPane().add(myPanel);
frame.setJMenuBar(myPanel.methodThatReturnsJMenuBar());
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();
}
});
}
}

Categories

Resources