Put a JLabel over two JButtons - java

Okay so before you ask, yes I'm not using any Layout Manager. No, that doesn't make this bad design (as I've seen people in here saying because someone simply didn't use one). The thing is i want the label to always (and I mean always) show over the two buttons (over the gap left by them which makes it impossible to put it as an Icon or a text on the JButton).
JFrame frame = new JFrame("ColorTap");
private void init() {
JButton jb1 = new JButton(""), jb2 = new JButton("-");
JLabel label = new JLabel("TEXT HERE");
label.setForeground(Color.white);
label.setFont(new Font("Arial Bold",Font.ITALIC,30));
label.setBounds(60,249,200,100);
frame.setLayout(null);
jb1.setBounds(0, 0, 300,298);
jb2.setBounds(0, 302, 300, 300);
jb1.setBackground(Color.black);
jb2.setBackground(Color.black);
jb1.setBorderPainted(false);
jb2.setBorderPainted(false);
frame.add(label);
frame.add(jb1);
frame.add(jb2);
frame.setResizable(false);
frame.setSize(300, 628);
frame.setLocation(550, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
After this what's stranger to me is that the button on the bottom stays under the label and not the one on the top... HELP! Thanks

Swing is optimized to paint components in two dimensions. That is it assumes components will never overlap. Overlapping JButtons cause a problem because of the rollover effects which only cause the buttons to be painted, not the label, so the button is painted over the top of the label.
So you need to tell Swing that components do overlap so Swing can make sure components are painted in the proper ZOrder:
JPanel panel = new JPanel()
{
#Override
public boolean isOptimizedDrawingEnabled()
{
return false;
}
};
Now you can set the layout manager of the panel and add your components to the panel and they will be painted properly.
See: How to put a JButton with an image on top of another JButton with an image? for a working example that DOES use layout managers.

Related

How to make a JButton that will create other buttons within a JPanel?

I am creating a user system to hold multiple details of multiple users. so i would like to create a button that would be able to create another button. when the second button is pressed a form will open for the user to fill. I have already created the form for the user to fill but i cannot manage to make the button to create more buttons to work. I have coded this but it does not show the button on the Jpanel.
I have created the following code:
private void mainButtonActionPerformed(java.awt.event.ActionEvent evt) {
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
jPanel3.add(b);
b.setVisible(true);
}
This doesn't seem to create a new button within jPanel3. Have I typed up the code incorrectly or is there an alternative correct way of doing this?
I would like 3 buttons in a row and then a new row of buttons.
Your code and question is missing too much information to be answered completely or well. About all I can say is
Always call jPanel3.revalidate() and jPanel3.repaint() on the container after adding or removing components from it as this tells the container's (here jPanel3) layout managers to re-layout all components and then re-draw them.
The container's layout manager is key for this to work well -- we have no idea what it is at the moment, and some layout managers will allow you to do this easily (e.g., FlowLayout, GridLayout) while others won't (e.g., GroupLayout).
There's no need for b.setVisible(true); since your newly created JComponent (JButton here) is already visible by default.
You appear to assume that it's using null layouts since you're calling setBounds(...), and this is a Bad Idea™. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
When asking such questions, try to create and post with the question a small but complete program that we can test and run, and that illustrates your problem, a minimal example program (please click on the link).
For example, my MCVE that shows how your code can work:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class AddButton extends JPanel {
private JPanel jPanel3 = new JPanel(); // panel to hold buttons
public AddButton() {
// create JButton that will add new buttons to jPanel3
JButton addMoreButtonsBtn = new JButton("Add More Buttons");
// give it an ActionListener
addMoreButtonsBtn.addActionListener(e -> {
final JButton newButton = new JButton("Click Here");
// when you click it, it removes itself (just for grins)
newButton.addActionListener(e2 -> {
jPanel3.remove(newButton);
// again revalidate and repaint
jPanel3.revalidate();
jPanel3.repaint();
});
// add to jPanel3, the "container"
jPanel3.add(newButton);
// revalidate and repaint the container
jPanel3.revalidate();
jPanel3.repaint();
});
// create a JPanel and put the add more buttons button to it
JPanel bottomPanel = new JPanel();
bottomPanel.add(addMoreButtonsBtn);
// give jPanel3 a layout that can handle new buttons
// a gridlayout with 1 column and any number of rows
jPanel3.setLayout(new GridLayout(0, 1));
// add it to the top of another JPanel that uses BorderLayout
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
borderLayoutPanel.add(jPanel3, BorderLayout.PAGE_START);
// and add that to a JScrollPane, so we can add many buttons and scroll
JScrollPane scrollPane = new JScrollPane(borderLayoutPanel);
// make the vert scrollbar always visible
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// force GUI to be larger
setPreferredSize(new Dimension(400, 200));
// give the main JPanel a BorderLayout
setLayout(new BorderLayout());
// and add scrollpane to center
add(scrollPane, BorderLayout.CENTER);
// add bottom panel to the bottom
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
AddButton mainPanel = new AddButton();
JFrame frame = new JFrame("AddButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

JButton added to JPanel doesn't show

I can't seem to add a JButton to a JPanel.
I have a PropWindow (JFrame) that has a PropView (JPanel) in it. the PropView-JPanel seems to be added correctly because I can draw shapes on it with paint().
But when I use this to try adding a button it just won't show up att all :/
JButton testButton;
public PropView(int width, int height) {
super(true);
setLayout(null);
setSize(width, height);
//TestButton
testButton = new JButton("Test");
testButton.setLocation(10,10);
testButton.setSize(100, 50);
testButton.setVisible(true);
add(testButton);
setFocusable(true);
setVisible(true);
}
The JFrame and the JPanel are both 250x600 px.
I can't tell from the code snippet you posted but just in case: make sure you call pack () on the frame after you have added the panel or any other components.
Also, it's usually discouraged to extend a JPanel or JFrame, unless you have a good reason to do it, just a heads up.
Here you have a short tutorial about displaying frames:
And some sample code in it that might help:
//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);
Make sure you added PropPanel to PropWindow using myPropWindow.getContentPane().add(myPropPanel), not just myPropWindow.add(myPropPanel).

JToolbar background and drag problems

I'm new to Swing and I currently work on some sort of graphic editor.
First I started implementing the toolbar (class OptionsBar) as an extended JPanel. Everything looked fine(image below), but it didn't work as a toolbar (it wasn't always focused). Then I found out that there actually exists a JToolBar element, so I replaced "extends JPanel" with "extends JToolBar". I look thorugh toolbar specifications. It seemed like I should change anything.
The problem is that the toolbar is transparent (besides its panel elements) even though isBackgroundSet() returns true. (image 2)
The second bug is drag the toolbar and then bring it back to the initial positions. It shrinks. (image 3)
Also, some movements (i can't describe them exactly) result in java.lang.IllegalArgumentException: illegal component position
The main windows is a JFrame that has border layout and uses a desktop pane.
Any help? Thanks!!
public class OptionsBar extends JToolBar {
..some constants and attributes..
public OptionsBar(BrushStroke brushStroke, BrushStroke savedBrushStroke) {
super();
this.setBackground(backgroundColor);
// keep the references to strokes from the main gui
this.brushStroke = brushStroke;
this.savedBrushStroke = savedBrushStroke;
// create buttons for selecting pencil/eraser
JToggleButton brushButton = makeInstrumentButton(brushIcon, "Pencil");
JToggleButton eraserButton = makeInstrumentButton(eraserIcon, "Eraser");
// make a button for adjusting colors
JButton adjustColorButton = makeAdjustButton();
// create label for descriptions
JLabel toolsLabel = makeDescriptionLabel("Tools");
JLabel parametersLabel = makeDescriptionLabel("Parameters");
JLabel colorsLabel = makeDescriptionLabel("Colors");
// create panel for brush size and opacity parameters
ParameterPanel sizePanel = new ParameterPanel("Size", "1", 1,
maxBrushSize, 1);
ParameterPanel opacityPanel = new ParameterPanel("Opacity", "100", 0,
100, 100);
// create a check box for selecting rounded caps
JCheckBox roundedCap = new JCheckBox("Use round strokes");
roundedCap.setSelected(true);
JSeparator separator = new JSeparator(JSeparator.VERTICAL);
separator.setMaximumSize(new Dimension(3, 35));
JSeparator separator1 = new JSeparator(JSeparator.VERTICAL);
separator1.setMaximumSize(new Dimension(3, 35));
// create a box layout
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.add(Box.createHorizontalStrut(20));
this.add(toolsLabel);
this.add(Box.createHorizontalStrut(30));
this.add(brushButton);
this.add(Box.createHorizontalStrut(10));
this.add(eraserButton);
this.add(Box.createHorizontalStrut(30));
this.add(separator1);
this.add(Box.createHorizontalStrut(30));
this.add(parametersLabel);
this.add(Box.createHorizontalStrut(20));
this.add(sizePanel);
this.add(Box.createHorizontalStrut(20));
this.add(opacityPanel);
this.add(Box.createHorizontalStrut(25));
this.add(roundedCap);
this.add(Box.createHorizontalStrut(25));
this.add(separator);
this.add(Box.createHorizontalStrut(30));
this.add(colorsLabel);
this.setOpaque(false);
addColorButtons();
this.add(Box.createHorizontalStrut(20));
this.add(adjustColorButton);
this.colorPicker = new ColorPicker();
colorPicker.getSelectionModel().addChangeListener(new ColorChange());
this.colorPopup = new JPopupMenu();
colorPopup.add(colorPicker);
this.setSize(2000, 65);
this.setVisible(true);
}
And here is the snipped from the JFrame constructor
Here is a snippet from the JFrame constructor
desktop = new JDesktopPane();
setContentPane(desktop);
whiteBoards = new HashMap<String, Canvas>();
createFrame("first try", 400, 300);
desktop.add(new OptionsBar(brushStroke,savedBrushStroke),BorderLayout.PAGE_START);
To give an answer to all your questions:
JMenuBar is transparent by default. You can change that setting as follows:
menuBar.setOpaque(true);
You added your JMenuBar to a JDesktopPane container. A JDesktopPane has no layout set by default, to allow positioning of the added JInternalFrame. Thats why your JMenuBar is not visible, if you do not set the size manually.
Usually it is a better idea to let the LayoutManager align your components. To do so, replace your last code snippet with these lines:
desktop = new JDesktopPane();
JPanel basePanel = new JPanel(new BorderLayout());
basePanel.add(desktop, BorderLayout.CENTER);
basePanel.add(new OptionsBar(...), BorderLayout.PAGE_START);
getContentPane().add(basePanel);
This code uses another parent JPanel which allows us to add our JMenuBar to the top area. Aligning and sizing of our JMenuBar is not delegated to the LayoutManager of the JPanel so we can get rid of the getSize(...) in the constructor of the OptionsBar.
I am pretty sure that this change also fixes the thrown IllegalArgumentException.

Having trouble re-sizing JButton in Java

Whenever I add my jbutton to my container it's really huge. I thought using the label.setBounds() function would work but it didn't
public Liability_Calculator(String s)
{
super(s);
setSize(325,200);
Color customColor = Color.WHITE;
c = getContentPane();
c.setLayout(new BorderLayout());
//the button
ok = new JButton("OK");
//ok.setSize(50, 50);
//HERE IS WHERE I TRY AND RESIZE!
ok.setBounds(30,30,50,50);
c.add(ok, BorderLayout.SOUTH);
setVisible(true);
}
Suggestions:
You will want to read up on the layout managers to
understand why your GUI is behaving this way
and to see how to use the layout managers to your advantage to create better looking GUI's in an easy way.
You'll also want to avoid setting bounds on any gui components.
For instance, a JPanel uses FlowLayout(FlowLayout.CENTER)) by default, and you can use that to your advantage by placing your ok JButton into a JPanel and then the JPanel into the contentPane:
ok = new JButton("OK");
// ok.setBounds(30, 30, 50, 50);
JPanel southPanel = new JPanel();
southPanel.add(ok);
c.add(southPanel, BorderLayout.SOUTH);
This will change the first image to the second:

Java Swing - JLabel Location

I have problem while setting the Jlabel location.
I set the content pane to some JPanel, I created and tried to add my JLabel.
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
mainTitle.setBounds(0,0, 115, 130);
getContentPane().add(mainTitle);
I want that my JPanel will be on the top left corner on my application and what I am getting is "SomeApp" on the top center.(and not top left).
btw I tried to add JButton the and the I can`t change the width,height,x,y of the JButton.
Swing uses Layout Managers to place the components.
You have to understand how they work to use them effectively. You can set the layout manager to null, and do the layout your self, but is not recommendable because you'll have to keep track of new components each time, and perform layout computation your self when the window moves shrink etc.
Layout managers are a bit hard to grasp at first.
Your windows could be like this:
Using this code:
import javax.swing.*;
import java.awt.Font;
import java.awt.FlowLayout;
class JLabelLocation {
public static void main( String [] args ) {
JLabel mainTitle = new JLabel("SomeApp");
mainTitle.setFont(new Font("Arial",2 , 28));
//mainTitle.setBounds(0,0, 115, 130); //let the layout do the work
JFrame frame = new JFrame();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
panel.add( mainTitle );
frame.add( panel );// no need to call getContentPane
frame.pack();
frame.setVisible( true );
}
}
Where a particular widget ends up in its container depends on the layout manager that it's using. The layout manager determines how to resize and arrange the widgets to make them fit appropriately. Obviously, the default layout for the content pane decided that the top center was the best place to put the JLabel.
If you want to get to not use a layout manager and just place everything yourself (which generally isn't the best way to lay things out btw), then add:
getContentPane().setLayout(null);
Using layouts is usually a better idea since they allow for dynamic resizing of components. Here's how you'd do it with a BorderLayout:
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add (new JLabel ("Main title"), BorderLayout.NORTH);
If you want to add something to the right of the label you could create an additionnal panel with it's own layout :
// Create a panel at the top for the title and anything else you might need
JPanel titlePanel = new JPanel (new BorderLayout());
titlePanel.add(new JLabel ("Main title"), BorderLayout.WEST);
// Add the title panel to the frame
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(titlePanel, BorderLayout.CENTER);
Here are some usefull links to get started with layouts:
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/visual.html
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/using.html

Categories

Resources