Hello I'm newish to Java and have recently attempted to go from using netbeans IDE to using raw code for making my JIternalFrames, but it displays either with no components or not at all.
To correct the issue I have attempted to move around the order in which I set up components for example I originally had it as initvariables > addcomponentstopanes > setsizes/text > setvisible, i've also tried using repaint() and revalidate() to no avail.
package tester;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestChunk extends javax.swing.JInternalFrame
{
JInternalFrame consumeWindow;
JScrollPane coScrollPane;
JPanel panel;
JButton eatBerriesButton, eatMushroomsButton, eatFishButton;
public void startComponents()
{
consumeWindow = new JInternalFrame("Consume Panel");
panel = new JPanel();
eatBerriesButton = new JButton();
eatMushroomsButton = new JButton();
eatFishButton = new JButton();
GridLayout myLayout;
consumeWindow.setBorder(null);
consumeWindow.setResizable(true);
myLayout = new GridLayout(0, 3, 10, 5);
panel.setLayout(myLayout);
consumeWindow.setSize(500, 325);
panel.setSize(500, 650);
eatBerriesButton.setBounds(5, 5, 150, 50);
eatMushroomsButton.setBounds(5, 60, 150, 50);
eatFishButton.setBounds(5, 105, 150, 50);
panel.add(eatMushroomsButton);
panel.revalidate();
panel.repaint();
panel.add(eatBerriesButton);
panel.revalidate();
panel.repaint();
panel.add(eatFishButton);
panel.revalidate();
panel.repaint();
coScrollPane = new JScrollPane(panel);
coScrollPane.setSize(500, 325);
coScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
coScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
consumeWindow.setContentPane(coScrollPane);
consumeWindow.revalidate();
consumeWindow.repaint();
consumeWindow.setVisible(true);
consumeWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The problem is my newest JInternalFrame (The one written entirely in code) isn't displaying and when I do get it to display it doesn't have any of it's components. The internal frame as it currently is should contain 3 buttons within a JScrollPane with about a 5 gap between each button. (If you'd like more code for clarification feel free to request it).
Related
I can see the button and when I get rid of the button, I can see the JLabelI'm using the Eclipse IDE and I'm trying to have a JLabel display over a JButton.
I already tried creating my JLabel above my JButton, still doesn't work
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Since you posted an image of your code fragment, I created the following GUI.
I should post an image of the code, but I'm going to be nice and post the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JLabelOverJButtonGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JLabelOverJButtonGUI());
}
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JLabel label = new JLabel("Label");
panel.add(label);
JButton button = new JButton("Button");
panel.add(button);
return panel;
}
}
JLabel showing ellipses when is has space to show full label
my code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.basic.BasicLookAndFeel;
import com.bulenkov.darcula.DarculaLaf;
public class GUI implements ActionListener {
private int count = 0;
private JLabel label;
private JFrame frame;
private JPanel panel;
public GUI() throws UnsupportedLookAndFeelException {
BasicLookAndFeel darcula = new DarculaLaf();
UIManager.setLookAndFeel(darcula);
frame = new JFrame();
JButton button = new JButton("Click Me");
button.addActionListener(this);
label = new JLabel("Number of clicks: 0");
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(20, 100, -85, 100));
panel.setLayout(new GridLayout(5, 1));
panel.add(button);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
///frame.setTitle("Cool GUI");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws UnsupportedLookAndFeelException {
new GUI();
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Number of clicks: " + count);
}
}
Oracle has a good tutorial that teaches the basics of Swing, Creating a GUI With JFC/Swing. Skip the Netbeans section.
I created the following GUI.
Here's what I did.
I started my Swing GUI with a call to the SwingUtilities invokeLater method. This method ensures that all of the Swing components are created and executed on the Event Dispatch Thread.
I separated the code to construct the JFrame from the code to construct the JPanel. The JFrame methods have to be called in a certain order. This is the order I use for most of my Swing applications.
I construct the JPanel in Swing component order. I keep all methods having to do with a particular Swing component together.
I put the "Number of clicks:" text in one place.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BasicGUI implements ActionListener, Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new BasicGUI());
}
private int count;
private JLabel label;
public BasicGUI() {
this.count = 0;
}
#Override
public void run() {
JFrame frame = new JFrame("Cool GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton button = new JButton("Click Me");
button.addActionListener(this);
panel.add(button);
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
updateLabel(0);
panel.add(label);
return panel;
}
public void updateLabel(int count) {
label.setText("Number of clicks: " + count);
}
#Override
public void actionPerformed(ActionEvent event) {
updateLabel(++count);
}
}
BasicLookAndFeel darcula = new DarculaLaf();
UIManager.setLookAndFeel(darcula);
Don't use a 3rd party LAF when asking a basic question.
We don't know if the problem is related to the LAF or the standard classes of the JDK.
JLabel showing ellipses when is has space to show full label
Well actually it doesn't have space because you use the pack() method and all components are displayed at their preferred size based on the preferred size of the components and of the Borders applied to the components.
When I run your code (using the default LAF) the text displays correctly at startup.
This is because the width of the panel is controlled by the preferred width of the JButton since it is the larger component.
However, if I change the text of the button to be:
label.setText("Number of clicks made: " + count);
now the width of the panel is controlled by the preferred width of the label since it is greater than that of the button.
Again, at startup the text displays properly
However, if you click the button 10 times then the "count" changes from a one digit number to a two digit number which increases the preferred size of the label causing the "..." to appear.
A simple solution is to use:
count++;
label.setText("Number of clicks made: " + count);
frame.pack();
Now the frame will be resized to accommodate the newly calculated preferred size of the label.
panel.setLayout(new GridLayout(5, 1));
Also, don't hardcode the "rows" of the GridLayout. The above code reserves space for 5 components even though you only have 2.
Instead use:
panel.setLayout(new GridLayout(0, 1));
which indicates a single column with any number of components.
Then you can use the EmptyBorder properly to give it symmetry on all sides:
//panel.setBorder(BorderFactory.createEmptyBorder(20, 100, -85, 100));
panel.setBorder(BorderFactory.createEmptyBorder(20, 100, 20, 100));
I think GridBagLayout asks your JLabel about the required size when the UI is initialized. Then the JLabel is assigned the requested size.
During runtime the String that needs to be displayed by the JLabel changes, and actually it gets longer. But no re-layout is happening, therefore the JLabel is not allowed to use more space - even if on the screen it seems there is plenty of space.
The solution is to either tell GridBagLayout to reserve plenty of space for that component, or allow for dynamic scaling. Check the GridBagLayout tutorial for details.
I tried to make a JButton that would put a JLabel in the window, but when I click the button, it doesn't seem to put the JLabel in the window. The button seems to work when I use it for the console, but not for putting the JLabel in the window. Why is this, and what should I do?
Here's my code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AnimaleseTranslator implements ActionListener {
private static JPanel panel;
private static JLabel label;
public AnimaleseTranslator() {
JFrame frame = new JFrame();
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(220, 391, 220, 391));
panel.setLayout(new GridLayout(0, 1));
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null); // centers the JFrame
frame.setTitle("Animalese Translator");
frame.setVisible(true);
JButton button = new JButton("Click me!");
button.setBounds(100, 100, 98, 55);
button.addActionListener(this);
panel.add(button);
label = new JLabel("lkdsajflksdjlaskdjf");
label.setBounds(200, 200, 50, 50);
}
public static void main(String[] args) {
new AnimaleseTranslator();
}
#Override
public void actionPerformed(ActionEvent e) {
panel.add(label);
}
}
but when I click the button, it doesn't seem to put the JLabel in the window.
The setBounds(...) statement does nothing. Swing uses layout managers by default and the layout manager will set the size/location of each component. So get rid of the setBounds() statement because it is confusing.
Components need to be added to the frame BEFORE the frame is made visible. The pack() or setVisible() statement will then invoke the layout manager.
After you add a component to panel on a visible frame you need to invoke panel.revalidate() to invoke the layout manager. So you need to add the revalidate() in the ActionListener.
Get rid of the setBorder(...) statement until you better understand what it does. The problem with your current code is the border is too big, so there is no room for the button and label to display properly.
I'm trying to create something super basic but after getting super frustrated I figured it was time to ask here.
Desired result:
Right now here is my code:
GUI class
package bookingProject;
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class GUI extends javax.swing.JFrame {
JFrame frame = new JFrame();
JPanel silverPanel = new JPanel();
JPanel goldPanel = new JPanel();
Button buttons[] = new Button[30];
public static void main(String args[]) {
new GUI();
}
public GUI() {
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel bronzePanel = new JPanel();
bronzePanel.setLayout(new GridLayout(3, 10));
bronzePanel.setBackground(Color.red);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
bronzePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
bronzePanel.add(buttons[i]);
}
add(bronzePanel);
setVisible(true);
silverPanel.setLayout(new GridLayout(3, 10));
silverPanel.setBackground(Color.yellow);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
silverPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
silverPanel.add(buttons[i]);
}
add(silverPanel);
setVisible(true);
goldPanel.setLayout(new GridLayout(3, 10));
goldPanel.setBackground(Color.green);
for (int i = 0; i < 30; i++) {
buttons[i] = new Button();
goldPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
goldPanel.add(buttons[i]);
}
add(goldPanel);
setVisible(true);
}
}
And a class for the Buttons I want to use
Button class
package bookingProject;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Button extends JButton implements ActionListener{
public Button (){
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source instanceof GUI){
((GUI)source).setBackground(Color.YELLOW);
}
}
}
This is what I'm getting:
I'm brand new to this stuff so forgive my complete ignorance/ability... but what I would like is 3 panels going top to bottom (bronze/silver/gold) each with a GridLayout of buttons... But all I can get is the bronze panel sticking infront of everything else. I think I'm supposed to use BoxLayout to sort the 3 panels into an order but I played around with this for about 4 hours and felt like I was getting nowhere fast.
I also need a way of making the buttons turn yellow when I press them but currently that isn't working; although I barely looked at that.
This is what I'm getting:
By default the content pane of a JFrame uses a BorderLayout. When you add components to the frame the components get added to the BorderLayout.CENTER by default because you didn't specify a constraint. Only one component can be displayed in the CENTER so only the last one added is visible.
I think I'm supposed to use BoxLayout
That is one approach (but probably not the easiest) as you would manually need to specify the space between each row of components.
The section from the Swing tutorial on How to Use Box Layout has a working example to get you started.
Easiest is to use a GridLayout with 3 rows and 2 columns as the layout manager for the frame. Then each individual panel can also use a GridLayout with 3 rows and 5 columns.
If you want spaces between the components in each of your panels then you need to look at the GridLayout API. It allows you to specify a vertical and horizontal gap between components.
Another approach would be to use a GridBagLayout, although this is a little more complicated because you need to specify constraints for each component added.
The tutorial also has sections on How to Use GridBag Layout and How to Use GridLayout.
Note the examples from the tutorial will also show you how to better structure your code so that component are created on the Event Dispatch Thread(EDT).
You can try GridBagLayout instead:
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import java.awt.Insets;
import java.awt.Color;
class Demo{
public static void main(String[]args){
SwingUtilities.invokeLater(()->{
JFrame frame=new JFrame("Grid");
JPanel panel=(JPanel)frame.getContentPane();
GridBagConstraints gbc=new GridBagConstraints();
gbc.insets=new Insets(9,7,5,5);
panel.setLayout(new GridBagLayout());
panel.add(newGrid(Color.YELLOW,gbc, 0, 0),gbc);
panel.add(newGrid(Color.YELLOW,gbc, 1, 0),gbc);
panel.add(newGrid(Color.LIGHT_GRAY,gbc, 0, 1),gbc);
panel.add(newGrid(Color.LIGHT_GRAY,gbc, 1, 1),gbc);
panel.add(newGrid(Color.GREEN,gbc, 0, 2),gbc);
panel.add(newGrid(Color.GREEN,gbc, 1, 2),gbc);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
});
}
private static JPanel newGrid(Color color, GridBagConstraints pGbc, int pX, int pY){
JPanel panel=new JPanel(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
gbc.insets=new Insets(5,5,5,5);
for(int x=0;5>x;x++){
for(int y=0;3>y;y++){
gbc.gridx=x;
gbc.gridy=y;
JButton btn=new JButton("<html> </html>");
btn.setBackground(color);
panel.add(btn,gbc);
}
}
pGbc.gridx=pX;
pGbc.gridy=pY;
return panel;
}
}
I want to add a jPanel which is semi transparent. But other components which are placed inside the jPanel such as buttons and labels should be displayed with 100% opacity. I am using netbeans to design the GUIs. Normally i drag and drop the swing components in the palette to design the GUI(I don't code them). I can't see any property in properties window to achieve this. Please help me. As I am quite new to java please give me a detailed answer. Thanks in advance.
You can use
JPanel.setBackground(Color bg);
to make the panel semi-transparent. What matter is the color's property.
You can construct a color with alpha values to set the transparent degree of the color.
panel.setBackground(new Color(213, 134, 145, 123));
The last parameter is actual the alpha value and you can adjust it to see the effect.
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PanelTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
PanelTest test = new PanelTest();
test.createUI();
}
};
SwingUtilities.invokeLater(runnable);
}
public void createUI(){
JFrame frame = new JFrame("Panel Test");
JPanel panel = new JPanel();
panel.setBackground(new Color(213, 134, 145, 123));
JButton button = new JButton("I am a button");
JLabel label = new JLabel("I am a label");
label.setFont(new Font("Arial", Font.BOLD, 15));
JTextField textField = new JTextField();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(Box.createVerticalStrut(20));
panel.add(label);
panel.add(Box.createVerticalStrut(20));
panel.add(textField);
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
BottomPanel buttomPanel = new BottomPanel();
buttomPanel.add(panel);
frame.add(buttomPanel,BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class BottomPanel extends JPanel{
#Override
protected void paintComponent(Graphics g) {
for (int y = 0; y < 200; y = y + 20) {
g.drawString("I am the string on the bottom", 5, y);
}
}
}
}
Here is the effect and hope it can help you.
You can simply create your jPanel using drag and drop, as you always do and then for changing the panel's color and making it transparent or semi-transparent you can use this code:
panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));
You can change the color by changing first three parameters of Color constructor, which represent RGB and you can change transparency by changing fourth parameter, which is the alpha value of color.