我正在开发一个项目,我要求在单击按钮时,GridBagLayer中的对象移动到不同的位置。到目前为止,这是我的代码:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class main extends JFrame{
private JButton button,littlebutton;
private JLabel holdred1,holdred2;
private ImageIcon red1,red2;
public main(){
//sets the layout
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//sets the button
button = new JButton("Button");
c.gridx = 0;
c.gridy = 0;
add(button,c);
//sets the image
red1 = new ImageIcon(getClass().getResource("/images/redtile.png"));
red2 = new ImageIcon(getClass().getResource("/images/redtile.png"));
//puts it in the JLabel
holdred1 = new JLabel(red1);
c.gridx = 0;
c.gridy = 0;
add(holdred1, c);
holdred2 = new JLabel(red2);
c.gridx = 1;
c.gridy = 0;
add(holdred2, c);
littlebutton = new JButton("Click Me");
c.gridx = 0;
c.gridy = 0;
add(littlebutton,c);
event e = new event();
littlebutton.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
//code goes here
}
}
public static void main(String args[]){
//displaying the window
main gui = new main();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(575,575);
gui.setVisible(true);
gui.setTitle("Change Spot");
}
}
我对Grid Bag Layouts没有多少经验,所以我不知道如何做到这一点,提前谢谢!
问题是如何让按钮将gridx更改为1
答案 0 :(得分:0)
在GridBagConstraints
中,您可以指定元素在网格中的位置。你已经在这部分代码
c.gridx = 0;
c.gridy = 0;
add(holdred1, c);
holdred2 = new JLabel(red2);
c.gridx = 1;
c.gridy = 0;
add(holdred2, c);
littlebutton = new JButton("Click Me");
c.gridx = 0;
c.gridy = 0;
但是您要告诉布局使用c.gridx = 0, c.gridy = 0
将多个组件放在同一个网格中。每个组件都应该有自己的单元格空间,因此它们不会重叠。
我编辑了你的代码:
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//sets the button
button = new JButton("Button");
c.gridx = 2;
c.gridy = 2;
add(button, c);
//sets the image
// red1 = new ImageIcon(getClass().getResource("/images/redtile.png"));
// red2 = new ImageIcon(getClass().getResource("/images/redtile.png"));
//puts it in the JLabel
holdred1 = new JLabel("Red1");
c.gridx = 1;
c.gridy = 1;
add(holdred1, c);
holdred2 = new JLabel("Red2");
c.gridx = 1;
c.gridy = 2;
add(holdred2, c);
littlebutton = new JButton("Click Me");
c.gridx = 2;
c.gridy = 1;
add(littlebutton, c);
event e = new event();
littlebutton.addActionListener(e);
我认为您希望标签位于按钮顶部,因此我将它们放在一边,以便您可以练习它。
另一个简单的提示,如果您希望组件在表格中占用多个单元格,则必须使用c.weightx = someValue, c.weighty = someValue
。