Moving text from a textfield to textarea with a button - java

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());
}
});

Related

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.

prevent GridBagLayout from resizing columns

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);
}
}

Aligning panels with GridBagLayout

I'm not exactly new to java (I've been using it for a year now) but this is my first go at swing. I'm trying to make a very simple chat client to learn both socket and swing at once. My question is "What must I do to align my panels correctly?". I've tried a lot of things (Though I don't have it in my code). Usually I work something like this out on my own, but I'm to the point I need to ask for help. Do I need to change the wieghtx, weighty? What I want the client to look like is something like this.
This is what it currently looks like.
Here is my code.
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
GridBagConstraints c = new GridBagConstraints();
//Main Panel
JPanel window = new JPanel();
window.setLayout(new GridBagLayout());
window.setBackground(Color.black);
//Panels
JPanel display = new JPanel();
JPanel chat = new JPanel();
chat.setLayout(new GridBagLayout());
JPanel users = new JPanel();
display.setBackground(Color.blue);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(display, c);
chat.setBackground(Color.red);
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 1;
c.insets= new Insets(5,5,5,5);
window.add(chat, c);
users.setBackground(Color.green);
c.gridx = 2;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(users, c);
//Buttons
//Text fields
JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
c.gridx = 0;
c.gridy = 0;
chat.add(text);
JTextField input = new JTextField("type here to chat", 50);
c.gridx = 0;
c.gridy = 1;
c.insets= new Insets(5,5,5,5);
chat.add(input);
add(window);
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
}
If you wanted something like this as an output :
You can take help from this code example, though you can remove the last ButtonPanel if you don't need that :
package to.uk.gagandeepbali.swing.messenger.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;
public class ChatPanel extends JPanel
{
private JButton backButton;
private JButton exitButton;
private JButton sendButton;
private JTextPane chatPane;
private JTextPane namePane;
private JTextField chatField;
private GridBagConstraints gbc;
private final int GAP = 10;
private final int SMALLGAP = 1;
public ChatPanel()
{
gbc = new GridBagConstraints();
}
protected void createGUI()
{
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
centerPanel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
chatPane = new JTextPane();
JScrollPane scrollerChat = new JScrollPane();
scrollerChat.setBorder(BorderFactory.createTitledBorder("Chat"));
scrollerChat.setViewportView(chatPane);
centerPanel.add(scrollerChat, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
namePane = new JTextPane();
JScrollPane scrollerName = new JScrollPane(namePane);
scrollerName.setBorder(BorderFactory.createTitledBorder("Names"));
centerPanel.add(scrollerName, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
chatField = new JTextField();
chatField.setOpaque(true);
chatField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("")
, BorderFactory.createEmptyBorder(SMALLGAP, SMALLGAP, SMALLGAP, SMALLGAP)));
centerPanel.add(chatField, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
sendButton = new JButton("Send");
sendButton.setBorder(BorderFactory.createTitledBorder(""));
centerPanel.add(sendButton, gbc);
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(true);
bottomPanel.setBackground(Color.WHITE);
bottomPanel.setBorder(
BorderFactory.createTitledBorder(""));
bottomPanel.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
backButton = new JButton("Back");
exitButton = new JButton("Exit");
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
bottomPanel.add(buttonPanel, BorderLayout.CENTER);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public JTextPane getChatPane()
{
return chatPane;
}
public JTextPane getNamePane()
{
return namePane;
}
public JTextField getChatField()
{
return chatField;
}
public JButton getExitButton()
{
return exitButton;
}
public JButton getBackButton()
{
return backButton;
}
public JButton getSendButton()
{
return sendButton;
}
}
What you could do, and probably gives the desired result
JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;
JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );
JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );
Way simpler then messing with GridBagLayout
Here is what I came out with thus far. The red box is where I plan to add a simple 2D avatar interface with LWJGL.
Here is the code for it
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Main Panels
JPanel window = new JPanel(new BorderLayout());
JPanel center = new JPanel(new BorderLayout());
JPanel right = new JPanel(new BorderLayout());
//Panels
JPanel display = new JPanel( new BorderLayout());
display.setBackground(Color.red);
JPanel chat = new JPanel();
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
JPanel users = new JPanel(new BorderLayout());
users.setBackground(Color.green);
//TextFields
JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50);
chatBox.setEditable(false);
JTextField chatWrite = new JTextField();
JScrollPane userList = new JScrollPane();
JTextField userSearch = new JTextField(10);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(chatBox);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
//Menu bar
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem ipconnect = new JMenuItem("Connect to IP");
file.add(ipconnect);
file.add(exit);
menu.add(file);
//Main window adding
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
//Listeners
chatWrite.addKeyListener(new KeyLis());
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
static class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println("Message recieved.");
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "Exit"){
System.exit(0);
} else if(e.getActionCommand() == "Connect to IP"){
System.out.println("Connecting....");
JFrame frameip = new JFrame();
JPanel panelip = new JPanel();
JButton buttonip = new JButton("Hello");
frameip.add(panelip);
panelip.add(buttonip);
JDialog ippop = new JDialog(frameip, "Enter IP", false);
}
}
}
}
I had to build a similar layout using a GridBagLayout. The code below shows how I achieved it.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutTest {
public GridBagLayoutTest() {
JFrame jframe = new JFrame();
jframe.setLayout(new GridBagLayout());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(800, 600);
jframe.setVisible(true);
// Left
JPanel leftPanel = new JPanel(new GridBagLayout());
leftPanel.setBackground(Color.YELLOW);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .7f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
jframe.add(leftPanel, gridBagConstraints);
JPanel leftTopPanel = new JPanel(new FlowLayout());
leftTopPanel.setBackground(Color.RED);
GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .7f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 0;
leftPanel.add(leftTopPanel, gridBagConstraints0);
JPanel leftMiddlePanel = new JPanel(new FlowLayout());
leftMiddlePanel.setBackground(Color.BLACK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .2f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 1;
leftPanel.add(leftMiddlePanel, gridBagConstraints0);
JPanel leftBottomBottomPanel = new JPanel(new FlowLayout());
leftBottomBottomPanel.setBackground(Color.PINK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .1f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 2;
leftPanel.add(leftBottomBottomPanel, gridBagConstraints0);
// Right
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.GREEN);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .3f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
jframe.add(rightPanel, gridBagConstraints);
}
public static void main (String args[]) {
new GridBagLayoutTest();
}

Categories

Resources