java JPanels里面的JButtons,填满整个面板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14550255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JButtons inside JPanels, fill up the whole panel
提问by pelican_george
I've been struggling to set a specific size to a button inserted into a JPanel with a GridLayout.
我一直在努力为插入带有 GridLayout 的 JPanel 的按钮设置特定大小。
The button always fills up the whole panel, whereas if I remove the gridlayout, the button won't have the same behavior.
该按钮始终填满整个面板,而如果我删除 gridlayout,该按钮将不会具有相同的行为。
any hints?
任何提示?
package panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ColorDisplay {
private final int X = 100;
private final int Y = 100;
private final Dimension PANEL_SIZE = new Dimension(500,500);
private JTextField textRed;
private JTextField textGreen;
private JTextField textBlue;
private JLabel labelText, labelRed, labelGreen, labelBlue;
private JPanel displayPanel;
private JPanel textPanel;
private JPanel buttonPanel;
private JButton button;
private final Font font = new Font("Arial", Font.PLAIN, 22);
public static void main(String[] args) {
// TODO Auto-generated method stub
new ColorDisplay();
}
public ColorDisplay(){
JFrame mainFrame = new JFrame();
// make sure the program exits when the frame close
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Color Display");
mainFrame.setLocation(X,Y);
mainFrame.setPreferredSize(PANEL_SIZE);
// ensure an elastic layout
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.setLocationByPlatform(true);
mainFrame.add(getColorPanel());
mainFrame.add(getTextPanel());
mainFrame.add(getButtonPanel());
mainFrame.pack();
mainFrame.setVisible(true);
}
public JPanel getColorPanel(){
displayPanel = new JPanel(new BorderLayout());
labelText = new JLabel("Color Display", JLabel.CENTER);
Font fontColorDisplay = new Font("Arial", Font.PLAIN, 42);
labelText.setFont(fontColorDisplay);
displayPanel.add(labelText);
return displayPanel;
}
public JPanel getTextPanel(){
textPanel = new JPanel(new GridLayout(2,3));
labelRed = new JLabel("Red", JLabel.CENTER);
labelGreen = new JLabel("Green", JLabel.CENTER);
labelBlue = new JLabel("Blue", JLabel.CENTER);
textRed = new JTextField();
textGreen = new JTextField();
textBlue = new JTextField();
labelRed.setFont(font);
labelGreen.setFont(font);
labelBlue.setFont(font);
textRed.setFont(font);
textGreen.setFont(font);
textBlue.setFont(font);
textPanel.add(labelRed);
textPanel.add(labelGreen);
textPanel.add(labelBlue);
textPanel.add(textRed);
textPanel.add(textGreen);
textPanel.add(textBlue);
return textPanel;
}
public JPanel getButtonPanel(){
buttonPanel = new JPanel(new BorderLayout());
button = new JButton("Display Color");
button.addActionListener(new ButtonListener ()); // Add event handler
button.setFont(font);
button.setPreferredSize(new Dimension(100, 100));
buttonPanel.add(button);
return buttonPanel;
}
private int getColor(){
String colorCode = textRed.getText() + textGreen.getText() + textBlue.getText();
return Integer.parseInt(colorCode);
}
private boolean validateColor(String textValue){
boolean isValid = false;
try {
int num1 = Integer.parseInt(textValue);
if (num1 >= 0 && num1 <= 255)
isValid = true;
else
{
isValid = false;
JOptionPane.showConfirmDialog(null, "Please enter numbers between 0 and 255", "Error", JOptionPane.PLAIN_MESSAGE);
}
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numerical values", "Error", JOptionPane.PLAIN_MESSAGE);
}
return isValid;
}
private class ButtonListener implements ActionListener { // Inner class
public void actionPerformed(ActionEvent event) {
if (validateColor(textRed.getText()) && validateColor(textGreen.getText()) && validateColor(textBlue.getText()))
{
Color bgColor = new Color(getColor());
displayPanel.setBackground(bgColor);
}
}
}
}
回答by David Kroukamp
Your question is about GridLayout
but you show code using BorderLayout
:
您的问题是关于GridLayout
但您使用BorderLayout
以下代码显示代码:
buttonPanel = new JPanel(new BorderLayout());
button = new JButton("Display Color");
button.addActionListener(new ButtonListener ()); // Add event handler
button.setFont(font);
button.setPreferredSize(new Dimension(100, 100));
?
?
The button always fills up the whole panel, whereas if I remove the gridlayout, the button won't have the same behavior.
该按钮始终填满整个面板,而如果我删除 gridlayout,该按钮将不会具有相同的行为。
This is GridLayout
default behavior, it space is divided equally and each component takes up the full space (same would apply for BorderLayout
).
这是GridLayout
默认行为,它的空间被平均划分,每个组件都占据整个空间(同样适用于BorderLayout
)。
There are many other LayoutManager
s which will will meet your needs:
还有许多其他LayoutManager
s 将满足您的需求:
You may want to look at GridBagLayout
which is more flexible:
您可能想看看GridBagLayout
哪个更灵活:
buttonPanel = new JPanel(new GridBagLayout());
button = new JButton("Display Color");
button.addActionListener(new ButtonListener()); // Add event handler
button.setFont(font);
GridBagConstraints gc=new GridBagConstraints();
gc.fill=GridBagConstraints.HORIZONTAL;
gc.gridx=0;
gc.gridy=0;
? ? ? ??
buttonPanel.add(button,gc);
or even the default JPanel
FlowLayout
:
甚至是默认值JPanel
FlowLayout
:
buttonPanel = new JPanel();
button = new JButton("Display Color");
button.addActionListener(new ButtonListener()); // Add event handler
button.setFont(font);
buttonPanel.add(button);
Or a 3rd party LayoutManger
like MigLayout
.
或者LayoutManger
像MigLayout
.
Other suggestions:
其他建议:
Dont call
setPreferredSize(..)
rather overridegetPreferredSize()
and even than only do this when painting to theGraphic
s object or wanting to make a component bigger/smaller dont do this for Layout purposes thats aLayoutManager
s job.Also always remember to create and manipulate Swing components on the Event Dispatch Threadvia
SwingUtilities.invokeLater(Runnable r)
block
不要调用
setPreferredSize(..)
而是覆盖getPreferredSize()
,甚至不要只在绘制到Graphic
s 对象或想要使组件更大/更小时才这样做,不要为了布局目的而这样做,这是一项LayoutManager
s 工作。还要永远记住通过块在事件调度线程上创建和操作 Swing 组件
SwingUtilities.invokeLater(Runnable r)
回答by c.pramod
Replace your getButtonPanel() with this method ( I've used GroupLayout to make it work),
用这个方法替换你的 getButtonPanel()(我使用 GroupLayout 让它工作),
public JPanel getButtonPanel(){
JPanel jPanel1 = new JPanel();
button = new JButton("Display Color");
button.addActionListener(new ButtonListener ()); // Add event handler
button.setFont(font);
javax.swing.GroupLayout jPanel1Layoutx = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layoutx);
jPanel1Layoutx.setHorizontalGroup(
jPanel1Layoutx.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layoutx.createSequentialGroup().addContainerGap().addComponent(button, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
jPanel1Layoutx.setVerticalGroup(
jPanel1Layoutx.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layoutx.createSequentialGroup().addComponent(button, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(0, 12, Short.MAX_VALUE)));
return jPanel1;
}
Instead of 24 u can set button size that u prefer !
您可以设置您喜欢的按钮大小而不是 24 个!
回答by DarrenKing
Simply create a JPanel, and add that JPanel to the layout of the frame. Now inside that JPanel, lets call it holderPanel, you add the button. Now the button doesn't take up the entire space! Feel free to do some of the following to better suite your program:
只需创建一个 JPanel,并将该 JPanel 添加到框架的布局中。现在在 JPanel 中,我们称其为 holderPanel,然后添加按钮。现在按钮不会占据整个空间!随意执行以下一些操作以更好地适应您的程序:
holderPanel.setOpaque(false); //So the panel is invisible, but your button is
holderPanel.setBorder(new EmptyBorder(80, 50, 20, 130));
holderPanel.setOpaque(false); //So the panel is invisible, but your button is
holderPanel.setBorder(new EmptyBorder(80, 50, 20, 130));
回答by MMSA
Try this, it worked for me.
试试这个,它对我有用。
JFrame frame=new JFrame();
JPanel p1 = new JPanel(new GridLayout(2,1));
JLabel lb1= new JLabel("Test1");
JButton button1 = new JButton("Go to whatever");
button1.addActionListener();
JPanel p2=new JPanel();
p2.add(button1);
p1.add(p2);
frame.add(p1);