Reputation:
My java code below features a image and a button below I just want to add another button that is on the same x axis as the one the current button is on. I don't know how to do that. I thought I tried to manipulate abc.weightx and change it and it had no effect. I have included a pic of what I am trying to do below.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 0.5;
gbc.weighty = 0.4;
gbc.fill = GridBagConstraints.BOTH;
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
ImageIcon image = new ImageIcon(url);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel, gbc);
gbc.weightx = 0.9;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.NONE;
JButton b = new JButton("Click Here");
frame.add(b, gbc);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}}
Upvotes: 0
Views: 195
Reputation: 3098
You're not setting the gridx
and gridy
from your GridBagConstraint
so they probably won't appear where you want them to.
I'd suggest to follow @AndrewThompson's advice and go for a BorderLayout
with your main panel in the BorderLayout.CENTER
position, and your buttons in a separate JPanel
with the default FlowLayout
, that you'd put in the BorderLayout.SOUTH
position.
If you want to stick with GridBagLayout
:
gridx=0
gridy=0
gridwidth=2
weightx=1
weighty=1
gridx=0
gridy=1
gridx=1
gridy=1
I'm not posting code because you'll learn a lot more if you try it all yourself.
Upvotes: 1
Reputation: 168815
Put the buttons in a centered flow layout. Put the flow layout in the page end of a border layout.
Upvotes: 1