Java swing, creating a button in my paint component - java

public void paintComponent(Graphics g){
g.drawImage(back,0,0,this);
if(winner || loser){
g.setColor(Color.white);
g.setFont(new Font(null,Font.BOLD,55));
g.drawString("SCORE:",350,250);
g.drawString(""+score,600,250);
g.drawImage(enemy,100,500,this);
g.drawImage(enemy2,175,500,this);
g.drawImage(enemy3,250,500,this);
g.drawImage(enemy5,700,515,this);
g.drawImage(enemy6,775,515,this);
g.drawImage(enemy7,850,515,this);
g.drawImage(enemy4,495,515,this);
if(winner){
g.drawImage(winnerPic,200,50,this);
}
else{
g.drawImage(gameOver,220,50,this);
}
g.drawImage(endingTitle,190,590,this);
JButton menu=new JButton("Return to menu");
menu.setSize(200,100);
menu.setLocation(400,400);
}
}
How do I make a button appear on the screen. Please be very detailed, idk how to work with swings layout styles.

First of all you have a container (such as a JPanel for example) that is displayed on a JFrame.
After crating your button, you have to add it to the container. Most of the time you want your container to have a Layout, such as a BorderLayout.
JButton menu = new JButton("Back to the menu");
container.add(menu, BorderLayout.CENTER);
EDIT:
If this isn't the way you want to implement it, it will atleast help you understand the hierarchy.
public void buttonExample(){
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 100));
JButton button = new JButton("Return to the menu");
panel.add(button, BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}

Related

Change color of JButton without changing its shape

I want to change the color of JButton by:
JButton button = new JButton();
button.setBackground(Color.decode("#00a5ff"));
In order for change to occur, I have to add:
button.setOpaque(true);
button.setBorderPainted(false);
However, this remove the curves around the edges and thus changes the shape of the button. Is there a way to just simply change to color and keep the other properties? Another example is the changing of color (getting darker) when you press a button without having changed its color.
Here is some code that illustrates the difference between the two buttons:
public static void main(String[] args) {
JFrame frame = new JFrame("frame");
frame.setSize(new Dimension(300, 300));
JButton button1 = new JButton();
JButton button2 = new JButton();
button1.setPreferredSize(new Dimension(100,100));
button2.setPreferredSize(new Dimension(100,100));
button2.setBackground(Color.decode("#00a5ff"));
button2.setBorderPainted(false);
button2.setOpaque(true);
JPanel pane1 = new JPanel(new FlowLayout());
JPanel pane2 = new JPanel(new FlowLayout());
pane1.add(button1);
pane2.add(button2);
frame.add(pane1, BorderLayout.WEST);
frame.add(pane2, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Thanks
I literally just tested the following:
JFrame frame = new JFrame("frame");
frame.setSize(new Dimension(300, 300));
JButton button = new JButton();
button.setBackground(Color.decode("#00a5ff"));
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
It seemed to work, but I am working on Ubuntu Studio 16.04. If you notice that it does not work, then let me know. Could you please show the result of your white button or your failed button (if it still doesn't work)?
Perhaps you have something else going on in your code. I altered a small example I have and the color changes with only setBackground(Color) using regular Button and using JButton. See the following...
public static void main(String[] args) {
Frame frame = new Frame();
Panel panel = new Panel();
Button closeButton = new Button("Close");
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
}
});
closeButton.setBackground(Color.decode("#00a5ff"));
panel.add(closeButton);
frame.add(panel);
frame.setSize(200, 100);
frame.setLocation(200, 50);
frame.setVisible(true);
}

BoxLayout only showing last component added

Looked at some previous posts pertaining to my subject but too no avail.
Trying to align components using BoxLayout but I cannot get it to work. I have tinkered with it for some time now with different results but I can't figure it out. I have used the default FlowLayout with no problems, I am trying to learn and expand my knowledge and BoxLayout will be better for my program. I want everything to stay in alignment if the User resizes their application window. I've adjusted all the sizes this way after just trying to get it to work and failing.
package GUI;
import javax.swing.*;
import java.awt.*;
/**
* Created by Thunderfoot on 7/31/2016. Keep Growing!
* Graphical User Interface
* Needs 3 JPanels(Text area + scroll pane)(2 Buttons) (1 Button), a JTextArea, JScrollPane, and 3 JButtons
*/
public class PrimaryFrame extends JFrame {
//Class variables
private static JPanel panel1, panel2, panel3;
public static JTextArea output;
//Constructor
public PrimaryFrame() {
//Frame component attributes
final Dimension FRAME_SIZE = new Dimension(400, 400);
final Dimension PANEL1_SIZE = new Dimension(400, 250);
final Dimension PANEL2_SIZE = new Dimension(400, 40);
final Dimension PANEL3_SIZE = new Dimension(400, 40);
//JFrame is PrimaryFrame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(FRAME_SIZE);
setMaximumSize(FRAME_SIZE);
setTitle("Fighting Game");
//JPanel for Text
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.PAGE_AXIS));
panel1.setMinimumSize(PANEL1_SIZE);
panel1.setPreferredSize(PANEL1_SIZE);
panel1.setMaximumSize(PANEL1_SIZE);
panel1.setBackground(Color.BLACK);
//JPanel for Attack and Kick Buttons
panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.LINE_AXIS));
panel2.setMinimumSize(PANEL2_SIZE);
panel2.setPreferredSize(PANEL2_SIZE);
panel2.setMaximumSize(PANEL2_SIZE);
panel2.setBackground(Color.BLUE);
//JPanel for Power Attack Button
panel3 = new JPanel();
panel3.setLayout(new BoxLayout(panel3, BoxLayout.PAGE_AXIS));
panel3.setMinimumSize(PANEL3_SIZE);
panel3.setPreferredSize(PANEL3_SIZE);
panel3.setMaximumSize(PANEL3_SIZE);
panel3.setBackground(Color.ORANGE);
panel3.add(Box.createHorizontalGlue());
panel3.add(Box.createVerticalGlue());
//JTextArea & JScrollPane
output = new JTextArea();
output.setEditable(false);
JScrollPane outputScroller = new JScrollPane(output, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outputScroller.setMaximumSize(new Dimension(375, 250));
outputScroller.setBorder(BorderFactory.createLineBorder(Color.RED));
panel1.add(outputScroller);
panel1.add(Box.createHorizontalGlue());
panel1.add(Box.createVerticalGlue());
//Attack Button
JButton attackButton = new JButton(" ATTACK ");
attackButton.setMaximumSize(new Dimension(75, 30));
attackButton.setBorderPainted(true);
//Kick Button
JButton kickButton = new JButton(" KICK ");
kickButton.setMaximumSize(new Dimension(75, 30));
kickButton.setBorderPainted(true);
//Add components
panel2.add(attackButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
panel2.add(kickButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
//Power Attack Button
JButton powAttButton = new JButton(" POWER ATTACK ");
powAttButton.setMaximumSize(new Dimension(150, 30));
powAttButton.setBorderPainted(true);
panel3.add(powAttButton);
panel3.add(Box.createHorizontalGlue());
}
public void buildGUI() {
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
}
You have to set the Layout of your PrimaryFrame.
I suggest you add an additional line to your buildGUI() method:
public void buildGUI() {
//defines the Layout for the main Frame
this.setLayout(new GridLayout(3,1)) //its up to you wich Layout you use
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
Notice GridLayout(3,1) will generate a layout with three rows and one column

Java Swing, having a JComponent and a JPanel

I'm trying to add a JComponent to a JPanel and then display it in a window. I'm pretty sure I've got it right, but only the button in the panel shows ups.
//Component class
JFrame window=new JFrame("This is a window");
RcComponent component=new RcComponent();
JButton button= new Button("This is a button");
JPanel panel=new JPanel();
panel.add(component);
panel.add(button);
window.add(panel);
window.setVisible(true);
Only the button shows up in the created window. I'm not quite sure what I'm doing wrong.
By default a JPanel uses a FlowLayout and a FlowLayout respects the preferred size of all components added to it.
If RcComponent is a custom component then you need to override the getPreferredSize() method to return the Dimension of the component.
#Override
public Dimension getPreferredSize()
{
return new Dimension(...);
}
If you don't override this method, then the preferred size is 0, so there is nothing to display:
I believe you have missed the layout manager.
https://www.google.com/#q=java%20layout
public static void main(String[] args) {
JFrame window=new JFrame("This is a window");
JButton button= new JButton("This is a button");
JLabel lbl= new JLabel("This is a label");
JPanel panel=new JPanel();
panel.setLayout(new GridLayout());
panel.add(button);
panel.add(lbl);
window.add(panel);
window.setSize(new Dimension(200, 200));
window.setLocationRelativeTo(null);
window.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
window.setVisible(true);
}

Java Panel overlapping Menu

I am new to Java, so this question might be obvious.
I have this Initialization code:
frame = new JFrame();
frame.setTitle("Test");
frame.setBounds(100, 100, 512, 468);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new MyJPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setAlignmentY(Component.TOP_ALIGNMENT);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(0, 0));
panel.setMinimumSize(new Dimension(0, 0));
frame.getContentPane().add(panel, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
mntmOpenBBinary.setPreferredSize(new Dimension(149, 22));
mnFile.add(mntmOpenBBinary);
JSeparator separator = new JSeparator();
mnFile.add(separator);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mnFile.add(mntmExit);
MyJPanel is a custom class that extends the JPanel class. Just as a test, it just writes "test" to the screen in the paintComponent method:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.setFont(RenderFont);
g.drawString("TEST", 1, 1);
}
You can see from the image below that, for some reason, the drawString method is drawing behind the menu. The coordinates I give in drawString, I'd think, would be the coordinates relative to the JPanel window. Also, the JPanel is "filling" the entire space of the JFrame. I'd prefer that my MyJFrame be only 100x100, but it seems to always want to auto fill the JFrame. How can I solve these 2 issues?
The text is hidden by the menu bar because last parameter of drawString() is the text baseline, and not the upper bound: http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html#drawString(java.lang.String,%20int,%20int)
So you need to use something like:
g.drawString("TEST", 1, 50);
Or better, use Font.getStringBounds() to compute your text height:
Rectangle2D textBounds = g.getFont().getStringBounds("TEST", (((Graphics2D) g).getFontRenderContext());
And to avoid having your panel taking all Frame space, replace:
frame.getContentPane().add(panel, BorderLayout.CENTER);
with:
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(panel, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
Although, you should not need this:
panel.setAlignmentY(Component.TOP_ALIGNMENT);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(0, 0));
panel.setMinimumSize(new Dimension(0, 0));

Center align a jtable into a jscrollpane

I am using NetBeans. I turned off the auto-resize of JTable columns. Now it is aligned to the left side of scroll pane. How can I make it centered?
Found the solution. Have to add an extra panel.
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 400);
JButton button = new JButton("Click me");
button.setPreferredSize(new Dimension(200, 40));
JPanel panel = new JPanel();
panel.add(button);
JScrollPane scrollableArea = new JScrollPane(panel);
frame.add(scrollableArea);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Really a great and unexpected solution. Sometime java really acts weird. Here is the orginal post http://www.velocityreviews.com/forums/t600361-jscrollpane.html

Categories

Resources