prevent GridBagLayout from resizing columns - java

Another problem with swing. How can I stop GridBagLayout from respacing components if one of them changes size? For example, I have few columns, in one of which there is a JLabel with text "text". When I change it to "texttext" layout manager resizes the whole column. I don't want it to do that. Is there any way to prevent it?
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ResizeIssue {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
It is visible while 9 -> 10 or anytime text changes width.

GridBagLayout ignores maximumWidth/Height. There's not an easy way to set the maximum size of the JLabel.
But, what I think you really want is the layout to not shift when the text in the JLabel changes.
That can be done by making the JLabel wide enough to hold the largest value it needs to display. For example:
jLabel1.setFont(new Font("monospace", Font.PLAIN, 12));
FontMetrics fm = jLabel1.getFontMetrics(jLabel1.getFont());
int w = fm.stringWidth("0000");
int h = fm.getHeight();
Dimension size = new Dimension(w, h);
jLabel1.setMinimumSize(size);
jLabel1.setPreferredSize(size);
Update:
To center the label text, just add:
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

This might work:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ResizeIssue2 {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
//*
c.gridy = 1;
int w = 32; //incButton.getPreferredSize().width;
for(c.gridx=0;c.gridx<3;c.gridx++) {
panel.add(Box.createHorizontalStrut(w), c);
}
// */
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

Related

Spaces between elements in GridLayout and GridBagLayout

I am trying to create a grid of text fields which I envision would look like this:
I am trying to use Swing in order to do this but am having trouble creating the grid. I have tried both GridBagLayout and GridLayout in order to accomplish this but have had the same issue with both - I am unable to remove spaces between the text fields.
The above image is using grid bag layout. I have tried to change the insets as well as the weights of each text field but have not been able to get rid of the spaces between the fields.
The grid layout is slightly better:
But it has the same problem. I tried adding each text field to a JPanel and then created an empty border for each panel but this also did not work.
I have attached the code for both implementations. I am not committed to using a JTextField so if there is some other element that a user can type into I would be willing to try that out as well. Any help getting rid of the spaces between each text field would be greatly appreciated!
GridBagLayoutDemo
class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
GridBagLayout gbl = new GridBagLayout();
pane.setLayout(gbl);
GridBagConstraints c = new GridBagConstraints();
int rows = 2;
int cols = 2;
for(int i = 0; i < (rows + 1) * 3; i++){
JTextField textField = new JTextField(1);
textField.setFont( new Font("Serif", Font.PLAIN, 30) );
JPanel tempPanel = new JPanel();
tempPanel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
tempPanel.add(textField);
c.gridx = i % (rows + 1);
c.gridy = i / (cols + 1);
c.gridheight = 1;
c.gridwidth = 1;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
pane.add(tempPanel, c);
}
gbl.setConstraints(pane, c);
c.insets = new Insets(0,0,0,0);
}
public void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
GridBagLayoutDemo demo = new GridBagLayoutDemo();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
demo.createAndShowGUI();
}
});
}
}
GridLayoutDemo
class GridLayoutDemo {
public void createAndShowGUI() {
JFrame frame = new JFrame("GridLayout");
//frame.setOpacity(0L);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel parentPanel = new JPanel();
GridLayout layout = new GridLayout(3, 3, 0, 0);
layout.setHgap(0);
layout.setVgap(0);
parentPanel.setLayout(layout);
for(int i = 0 ; i < 9; i++){
JTextField textField = new JTextField();
textField.setHorizontalAlignment(JTextField.CENTER);
// JPanel tempPanel = new JPanel();
//textField.setBounds(0, 0, 10 , 10);
//textField.setFont( new Font("Serif", Font.PLAIN, 18));
//tempPanel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
//tempPanel.add(textField);
// tempPanel.add(textField);
parentPanel.add(textField);
}
frame.add(parentPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutDemo demo = new GridLayoutDemo();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
demo.createAndShowGUI();
}
});
}
}
I think you will find that this is a issue with the MacOS look and feel, as it adds a empty border around the text fields to allow for the focus highlight
You can see it highlighted below
The simplest way to remove it, is to remove or replace the border, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
int rows = 3;
int cols = 3;
for (int index = 0; index < (rows * cols); index++) {
int row = index % rows;
int col = index / cols;
gbc.gridy = row;
gbc.gridx = col;
JTextField textField = new JTextField(4);
textField.setText(col + "x" + row);
textField.setBorder(new LineBorder(Color.DARK_GRAY));
add(textField, gbc);
}
}
}
}

How to change frame on button event Java

I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}

Adding ChartPanel to CardLayout

I have a pretty basic GUI organized with a GridBagLayout. The most complex portion is the bottom where West is populated with ScrollPane and the right is a panel with a CardLayout that has multiple ChartPanels so I can switch between a few graphs.
My issue comes when I start the program.
The resizing issue goes away after I resize the frame in any direction. I have confirmed the chartpanel is the issue because not adding this to the CardLayout panel fixes it. I create a blank ChartPanel and populate it later after some action is taken but this is what I've done:
public class Tester {
public static void main(String[] args) {
JFrame frame = new JFrame("Chipmunk: Variant Data Collection Tool");
JPanel hotspotPanel = new JPanel(new CardLayout());
ChartPanel subHotspotPanel = new ChartPanel(null);
JPanel indelHotspotPanel = new JPanel(new BorderLayout());
JTextPane resultPane = new JTextPane();
JPanel main = new JPanel(new GridBagLayout());
JPanel header = new JPanel(new BorderLayout());
header.setBackground(Color.WHITE);
frame.setLayout(new BorderLayout());
frame.setMinimumSize(new Dimension(875, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
resultPane.setOpaque(false);
resultPane.setEditable(false);
GridBagConstraints c = new GridBagConstraints();
DocumentFilter filter = new UppercaseDocumentFilter();
JTextField geneField = new JTextField(10);
((AbstractDocument) geneField.getDocument()).setDocumentFilter(filter);
geneField.setMinimumSize(geneField.getPreferredSize());
JTextField proEffField = new JTextField(10);
proEffField.setMinimumSize(proEffField.getPreferredSize());
String[] mutTypes = { "missense", "nonsense", "frameshift", "nonframeshift"};
JComboBox<String> mutTypeComboBox = new JComboBox<String>(mutTypes);
JButton saveResultsButton = new JButton("Save to TSV");
JPanel glass = (JPanel) frame.getGlassPane();
JButton clearButton = new JButton("Clear");
JButton cosmicButton = new JButton("To COSMIC");
JButton dataButton = new JButton("Show Data");
dataButton.setEnabled(false);
JButton goButton = new JButton("GO");
c.weightx = 1.0;c.gridx = 0;c.gridy = 0;c.anchor = GridBagConstraints.EAST;c.ipadx=5;c.ipady=5;
main.add(new JLabel("Gene: "), c);
c.gridx = 1;c.gridy = 0;c.anchor = GridBagConstraints.WEST;
main.add(geneField, c);
c.gridx = 0;c.gridy = 1;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Protein Effect: "), c);
c.gridx = 1;c.gridy = 1;c.anchor = GridBagConstraints.WEST;
main.add(proEffField, c);
c.gridx =0;c.gridy = 2;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Mutation Type: "), c);
c.gridx =1;c.gridy = 2;c.anchor = GridBagConstraints.WEST;
main.add(mutTypeComboBox, c);
c.gridx =0;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(saveResultsButton, c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(goButton, c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(clearButton,c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.CENTER;
main.add(dataButton,c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(cosmicButton,c);
c.gridx = 0; c.gridy =4;c.gridwidth =1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
JScrollPane scrollPane = new JScrollPane(resultPane);
main.add(scrollPane, c);
c.gridx = 1; c.gridy =4;c.gridwidth = 1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
hotspotPanel.add(subHotspotPanel, "SUBPANEL");
hotspotPanel.add(indelHotspotPanel, "INDELPANEL");
hotspotPanel.add(new JPanel(), "BLANK");
main.add(hotspotPanel, c);
frame.add(header, BorderLayout.NORTH);
frame.add(main, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Using this example, it's clear that a ChartPanel works correctly in a CardLayout. The example below overrides getPreferredSize(), as shown here, to establish an initial size for the ChartPanel. The use of GridLayout on each card allows the chart to fill the panel as the enclosing frame is resized.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* #see https://stackoverflow.com/a/36392696/230513
* #see https://stackoverflow.com/a/36243395/230513
*/
public class CardPanel extends JPanel {
private static final Random r = new Random();
private static final JPanel cards = new JPanel(new CardLayout());
private final String name;
public CardPanel(String name) {
super(new GridLayout());
this.name = name;
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("One", r.nextInt(10) + 10);
pieDataset.setValue("Two", r.nextInt(20) + 10);
pieDataset.setValue("Three", r.nextInt(30) + 10);
JFreeChart chart = ChartFactory.createPieChart3D(
"3D Pie Chart", pieDataset, true, true, true);
chart.setTitle(name);
this.add(new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, (int)(500 * 0.62));
}
});
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 9; i++) {
CardPanel p = new CardPanel("Chart " + String.valueOf(i));
cards.add(p, p.toString());
}
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("\u22b2Prev") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.previous(cards);
}
}));
control.add(new JButton(new AbstractAction("Next\u22b3") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}));
f.add(cards, BorderLayout.CENTER);
f.add(control, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Fixed size of buttons

There is a JPanel with buttons and textField. TextField filters unnecessary buttons by name. But after delete the size of rest buttons is changing.
The height of buttons must not change after filtering in the textField. How to achieve this?
public class TestViewer {
public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new TestDialog();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setTitle("Type text and press Enter");
dialog.setSize(300, 700);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
dialog.setModal(true);
}
});
}
}
class TestDialog extends JDialog {
public TestDialog() {
getContentPane().add(new JPan
el(), BorderLayout.CENTER);
getContentPane().add(createBtnPanel(), BorderLayout.CENTER);
}
private JPanel createBtnPanel() {
int n = 100;
Final String ArrButtonNames[] = new String[n];
for (int h = 0; h < ArrButtonNames.length; h++) {
if ((h%2)==0){
ArrButtonNames[h]="Filter"+h;
}
else{
ArrButtonNames[h]="Button"+h;
}
}
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel(new GridLayout(0, ArrButtonNames.length, 1,1));
btnPanel.setLayout(new GridLayout(0, 1));
final JTextField textField = new JTextField();
textField.setColumns(23);
btnPanel.add(textField);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
Dimension d = button.getPreferredSize();
d.setSize(d.getWidth(), d.getHeight()*1);
button.setPreferredSize(d);
button.setSize(d);
button.setMinimumSize(d);
button.setMaximumSize(d);
btnPanel.add(button);
ArrButton[i] = button;
}
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int k = 0; k < ArrButtonNames.length; k++) {
if(ArrButtonNames[k].indexOf(textField.getText())==-1) {
btnPanel.remove(ArrButton[k]);
btnPanel.revalidate();
btnPanel.repaint();
}
}
}
});
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new BorderLayout());
MainPanel.add(btnPanel, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(btnPanel);
MainPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
return MainPanel;
}
}
You have that effect, because you use GridLayout, which resize components to fill whole cell.
For your purposes I recommend you to use GridBagLayout, that can do what you want.
Try to use next code for filling your btnPanel instead of yours:
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx=0;
c.gridy=0;
btnPanel.setLayout(new GridBagLayout());
final JTextField textField = new JTextField();
btnPanel.add(textField,c);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
c.gridy ++;
btnPanel.add(button,c);
ArrButton[i] = button;
}
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridy ++;
btnPanel.add(new JLabel(""),c);
And it looks like:
ALso use pack() method instead of setSize(...), and don't use setPreferedSize(...) and others size methods read about that here.

Moving text from a textfield to textarea with a button

This code compiles and runs but it does not copy the text from the text field then place it into the text area.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NameGameFrame extends JFrame
{
static JTextField textfield = new JTextField(20);
static JTextArea textarea = new JTextArea(30,30);
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Name Game");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel("Enter the Name or Partial Name to search:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
static class Action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//This is the code that should perform the task
String name = textfield.getText();
textarea.append(name);
}
}
}
I am new to Java programming and I apologize if my questions are simplistic.
Appen below code to your program after ther declaration of button
ie. JButton buuton = new JButton("Search");
button.addActionListener(new ActionAdapter()
{
public void actionPerformed(ActionEvent ae)
{
textarea.setText(textfield.getText());
}
});

Categories

Resources