Why are the bounds not working on this GUI - java

Why are the bounds on the panelFirst not working? It just displays everything at the top and it does not display the bounds in the order I have set them? The radio buttons should display in one under the other and the next button should display on the far right but it is not working?
public MyWizard() {
panelContainer.setLayout(c1);
panelFirst.add(btNext);
panelSecond.add(btNextTwo);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.RED);
panelThird.setBackground(Color.GREEN);
panelContainer.add(panelFirst, "1");
panelContainer.add(panelSecond,"2");
panelContainer.add(panelThird,"3");
c1.show(panelContainer, "1");
btNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
c1.show(panelContainer,"2");
}
});
btNextTwo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
c1.show(panelContainer,"3");
}
});
RadioButtons();
Button();
frame.add(panelContainer);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(600,360);
frame.setVisible(true);
}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panelFirst.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panelFirst.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panelFirst.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panelFirst.add(btSaml2);
}
public void Button() {
btNext.setBounds(400,260,100,20);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyWizard();
}
});
}
}

Assuming that panelFirst is (or extends from) something like JPanel, it will be under the control of a layout manager (in this case, most likely a FlowLayout).
It is highly recommended that you avoid setBounds, setLocation and setSize and instead rely on the layout managers
Graphical Interfaces are required to run on a variety of different platforms, each with unique rendering properties. To solve this issue, the developers of Java/Swing/AWT designed the LayoutManager API. This makes it easier to develop sophisticated user interfaces that will work on multiple different platforms
Take a look at Using Layout Managers and A Visual Guide to Layout Managers

If your radio buttons should be under each other, then create a panel for them, and set the panel's layout to BoxLayout like this:
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.add(...);
//then add p to the fram's container or to some other container

Related

JPanel ontop of other JPanels

I would like to make a JPanel pop up over an other JPanel in java. However I can not find anything useful on the internet. I tried playing around with absolute positioning but things like buttons from the bottom layer are showing through the top layer.
I uploaded a really ugly drawing of what I want to do.
Is there an easy way of doing this?
Edit:
I tried to make what "Ulkra" suggested. Here is the code and a screenshot:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(400, 400));
JPanel panel = new JPanel();
JPanel foregroundPanel = new JPanel();
foregroundPanel.setVisible(false);
foregroundPanel.setBackground(Color.BLUE);
foregroundPanel.setLayout(new BoxLayout(foregroundPanel, BoxLayout.Y_AXIS));
JPanel backgroungPanel = new JPanel();
backgroungPanel.setBackground(Color.RED);
backgroungPanel.setLayout(new BoxLayout(backgroungPanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 10; i++) {
backgroungPanel.add(new JButton("BackgroundBtn " + i));
}
foregroundPanel.add(new JButton("ForegroundBtn 1"));
JButton makeVisibleBtn = new JButton("+");
makeVisibleBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
foregroundPanel.setVisible(true);
}
});
backgroungPanel.add(makeVisibleBtn);
JButton makeInvisibleBtn = new JButton("-");
makeInvisibleBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
foregroundPanel.setVisible(false);
}
});
foregroundPanel.add(makeInvisibleBtn);
panel.add(backgroungPanel);
panel.add(foregroundPanel);
frame.add(panel);
}
}
For this, you have to use a Panel (if you are using NetBeans, you can find it in Swing Containers) and in the constuctor of the Frame, you have to SET IT AS UNVISIBLE, so you need the buttom to see it: (In this example, i call my Panel as "jPanel1" and i put a buttom in it)
public Main() {
initComponents();
jPanel1.setVisible(false);//<-- This!
this.setLocationRelativeTo(null);
}
Then, you create the buttom to "activate it" and but this code in:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.setVisible(true);
}
(And of course, if you wanna set it as unvisible you just have to do the same as in the constructor).
I test it and it works:(Imgur is not working so excuse i have to use postimg.org)
https://postimg.org/gallery/1z6fpajva/
Now you could put a border so you can differentiate your new Panel from your other Frame:
https://postimg.org/image/mdpf7hvxx/

Translucent loading overlay for JFrame

I have a JFrame containing various components and I would like to add a translucent grey overlay over the top while the application is initializing various things. Ideally it would prevent interaction with the underlying components and would be able to display some "Loading..." text or a spinning wheel or something similar.
Is there a simple way to do this using Java and Swing?
Take a look at JRootPane and JLayeredPane http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#layeredpane
What you're asking about specifically sounds like a Glass Pane.
http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#glasspane
The Glass Pane prevents interaction with underlying components and can be used to display something on top of your JFrame.
As #David said, you can use the glass pane for displaying some loading text or image above the rest of the application.
As for the grey overlay: why don't you use the built in ability to disable components as long as your application is loading? Disabled components will get grayed out automatically and cannot be interacted with by the user.
Something like this:
public class LoadingFrame extends JFrame{
JButton button;
public LoadingFrame() {
button = new JButton("ENTER");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Application entered");
}
});
setLayout(new BorderLayout());
add(button, BorderLayout.CENTER);
}
public void startLoading(){
final Component glassPane = getGlassPane();
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
final JLabel label = new JLabel();
panel.add(label, BorderLayout.SOUTH);
setGlassPane(panel);
panel.setVisible(true);
panel.setOpaque(false);
button.setEnabled(false);
Thread thread = new Thread(){
#Override
public void run() {
for (int i = 5; i > 0; i--) {
label.setText("Loading ... " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// loading finished
setGlassPane(glassPane);
button.setEnabled(true);
}
};
thread.start();
}
public static void main(String[] args) {
LoadingFrame frame = new LoadingFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.startLoading();
frame.setVisible(true);
}
}

windowbuilder in eclipse, unsure how to display window

I'm fairly new to Swing, so I've been using windowbuilder to try and put together a basic GUI. The design screen works fine, but when I return to the code, it's written it in a way I'm unfamiliar with and I'm struggling to actually get it to run.
The code it generates is:
public class GUIControls extends JFrame{
public GUIControls() {
getContentPane().setLayout(new CardLayout(0, 0));
JPanel panel = new JPanel();
getContentPane().add(panel, "name_36737116256884");
panel.setLayout(null);
JButton InsertionSortButton = new JButton("Insertion Sort");
InsertionSortButton.setBounds(32, 16, 101, 56);
panel.add(InsertionSortButton);
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1, "name_36737137352442");
InsertionSortButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
CardLayout cardLayout = (CardLayout) getContentPane().getLayout();
cardLayout.show(getContentPane(), "name_36737137352442");
}
});
}
(With the action taken when the button is mouseclicked being written by me, I haven't tested it because I can't run the thing)
Normally I'd do:
public void runGUI(){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
With createGUI being the method I used to create a (completely horrible) GUI without windowbuilder, but I can't use GUIControls in this because it doesn't work with runnable (in fact, I'm not even sure what it is when something doesn't a return value, is it still a method?).
Does anyone know how I go about running it?
Thanks
You need to instantiate an instance of GUIControls and make it visible, for example...
public void runGUI(){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIControls guiControls = new GUIControls();
guiControls.pack();
guiControls.setLocationRelativeTo(null);
guiControls.setVisible(true);
}
});
}
ps- I know Window Builder likes to make use of null layouts, but I would avoid them wherever possible - IMHO

How to use the built-in PLAF with custom components?

I'm creating a custom button, and I'm having trouble getting it to look right on most of the built-in PLAFs.
Here's my code
public MyButton(String text, Icon icon) {
if (icon == null) icon = createDefaultIcon();
mainButton = new JButton(text);
popupButton = new JButton(icon);
removeBorder(mainButton);
removeBorder(popupButton);
setModel(new DefaultButtonModel());
setBorder(UIManager.getBorder("Button.border"));
int popupButtonWidth = popupButton.getPreferredSize().width;
int popupButtonHeight = mainButton.getPreferredSize().height;
Dimension popupButtonSize = new Dimension(popupButtonWidth, popupButtonHeight);
popupButton.setMinimumSize(popupButtonSize);
popupButton.setPreferredSize(popupButtonSize);
popupButton.setMaximumSize(popupButtonSize);
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(mainButton);
add(new JSeparator(VERTICAL));
add(popupButton);
}
private void removeBorder(JButton button) {
Border border = button.getBorder();
if (border instanceof CompoundBorder) {
button.setBorder(((CompoundBorder) border).getInsideBorder());
} else {
button.setBorder(BorderFactory.createEmptyBorder());
}
}
Here is how the button looks in the PLAFs installed on my computer
Metal
Nimbus
CDE/Motif
Mac OS X
CDE/Motif is the only one that works properly. I looked at the source for some of the ButtonUIs, and it seems they can ignore the background color and the borders. Unfortunately the background color and the borders are what I need to set. How do I get my custom button to support the built-in PLAFs correctly?
Edit:
As requested, here's the code I used to produce the images
public class MyButtonDemo implements Runnable {
public void run() {
// Change the array index to get a different PLAF
try {
UIManager.setLookAndFeel(UIManager.getInstalledLookAndFeels()[0].getClassName());
} catch (Exception ignored) { }
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new MyButton("My Button", null);
frame.getContentPane().add(new JButton("Normal Button"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyButtonDemo());
}
}
Welcome to the wonderful world of pluggable look & feel. The only real choices you have, that I can think of, is provide. UI delegate for each platform or have a look at at the Syththetic UI
Not sure what I did, but it's working now for all but Nimbus. Here's the code
public MyButton(String text, Icon icon) {
arrowIcon = createDefaultArrowIcon();
mainButton = new JButton(text, icon);
popupButton = new JButton(arrowIcon);
mainButton.setBorder(BorderFactory.createEmptyBorder());
popupButton.setBorder(BorderFactory.createEmptyBorder());
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(mainButton);
add(new JSeparator(VERTICAL));
add(popupButton);
setModel(new DefaultButtonModel());
init(null, null);
}
#Override
public void updateUI() {
setUI((ButtonUI)UIManager.getUI(this));
}
#Override
public String getUIClassID() {
return "ButtonUI";
}

how to set new text in JTextField after creation?

I have a jTextField , and I set it's value to a certain sum when I create the frame.
Here is the initiation code:
totalTextField.setText(
itemsPriceTextField.getText() +
Float.toString(orderDetails.delivery)
);
This textfield should show a sum of items selected by the user.
The selection is done on a different frame, and both frames are visible / invisible
at a time.
The user can go back and forth and add / remove items.
Now, every time i set this frame visible again, I need to reload the value set to that field
(maybe no changes were made, but if so, I need to set the new correct sum) .
I'm quite desperate with it.
Can anyone please give me a clue?
Thanks in advance! :)
Before setting the frame visible again, one should update the fields with the new values / states.
something like:
jTextField.setText("put your text here");
jRadioButton.setSelected(!isSelected());
.
/* update all you need */
.
jFrame.setVisible(true);
The frame will come up with the new values / states.
Add a WindowListener to the frame. Then you can handle the windowActivated event and reset the text of the text field.
See How to Write Window Listeners.
Use a DocumentListener triggering the JTextField public void setText(String t)
Here an example with DocumentListener:
public class SetTextInJTextField extends JFrame implements DocumentListener {
JTextField entry;
JTextField entryToSet = new JTextField();
public SetTextInJTextField() {
createWindow();
entry.getDocument().addDocumentListener(this);
}
private void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createUI(final JFrame frame) {
JPanel panel = new JPanel();
entry = new JTextField();
entryToSet = new JTextField();
LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.add(this.entry);
panel.add(entryToSet);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
public void setTextInTargetTxtField() {
String s = entry.getText();
entryToSet.setText(s);
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void removeUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void changedUpdate(DocumentEvent ev) {
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SetTextInJTextField().setVisible(true);
}
});
}
}
inspired from: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextFieldDemoProject/src/components/TextFieldDemo.java
related lesson: https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

Categories

Resources