I've been trying to set fixed column width in the following code for ages...The thing is that when I add a label to the panel on the left, then the width is incremented automatically...and i Would like the column width to be fixed...
Could anyone help me please??
This is the code:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import java.io.IOException;
public class CurrentItem extends JPanel{
private static JFrame currentScreen;
public CurrentItem(JFrame p) {
GridBagConstraints c = new GridBagConstraints();
//Borramos todo lo que haya en la pantalla
this.removeAll();
this.revalidate();
currentScreen = p;
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new GridBagLayout());
currentScreen.add(this);
// --->
Panel leftPanel = new Panel();
leftPanel.setBackground(Color.BLACK);
c.weightx = 1.5;
c.weighty = 1;
//c.fill = GridBagConstraints.BOTH;
this.add(leftPanel, c);
// <---
// --->
Panel secondPanel = new Panel();
secondPanel.setBackground(Color.green);
c.weightx = 0.25;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
this.add(secondPanel, c);
// <---
// --->
Panel rightPanel = new Panel();
rightPanel.setBackground(Color.CYAN);
c.weightx = 1.5;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
this.add(rightPanel, c);
// <---
currentScreen.setVisible(true);
this.requestFocusInWindow();
}
}
GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be.
Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing behavior.
Generally weights are specified with 0.0 and 1.0 as the extremes: the numbers in between are used as necessary.
Read more How to Use GridBagLayout
Sample code: (below code set fixed width column with 100% vertical size.)
Panel leftPanel = new Panel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
};
Remove weightx for first column and override getPreferredSize() method.
leftPanel.setBackground(Color.BLACK);
c.weighty = 1;
c.fill = GridBagConstraints.VERTICAL;
this.add(leftPanel, c);
If you know ahead of time the labels that you'll be adding, and how wide each one is:
You can call label.getPreferredSize().width on each label to determine the width of the largest label.
Then, add an invisible component (Box.createHorizontalStrut(width)) to the column to force it to be that wide at all times.
Then, when you add all of your labels, the width of that column of the panel will not change.
Related
IN MY PROGRAM,
I have a button when pressed, adds a new JPanel to a JPanel with BOXLAYOUT. Since when I add the JPanel it adds it to the bottom of the previous one. BUT THERE IS NO SCROLL BAR.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class tes{
public static void main(String[] args) {
JFrame newL = new JFrame();
newL.setTitle("New Level Files");
//newL.setLayout(new BoxLayout());
//t.setSize(500,600);
//newL.pack();
newL.setVisible(true);
newL.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(listPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(600, 100));
newL.add(scrollPane, BorderLayout.CENTER);
JPanel levelP = new JPanel();
levelP.setBorder(BorderFactory.createLineBorder(Color.black));
levelP.setLayout(new GridBagLayout());
GridBagConstraints l = new GridBagConstraints();
l.insets = new Insets(10,10,10,5);
JButton okForFileEdit = new JButton("Edit this File");
l.gridx = 1;
l.gridy = 6;
levelP.add(okForFileEdit, l);
okForFileEdit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent n){
JPanel createInPanel = new JPanel();
createInPanel.setSize(200,200);
createInPanel.setBorder(BorderFactory.createLineBorder(Color.black));
createInPanel.setLayout(new GridBagLayout());
listPane.add(createInPanel);
JLabel yout = new JLabel("YEah this is a long sentence to see the placement");
createInPanel.add(yout);
listPane.revalidate();
listPane.repaint();
newL.revalidate();
}});
listPane.add(levelP);
listPane.revalidate();
listPane.repaint();
newL.add(listPane);
newL.pack();
}
** I added a SIMPLIFIED VERSION OF THE PROGRAM THAT DOESN'T MAKE THE SCROLLBAR
Hope this makes more sense. Thanks for the help in advance :);
I have a button when pressed, adds a new JPanel to a JPanel with BOXLAYOUT.
When you dynamically add components to a panel the basic logic need in your ActionListener is:
panel.add(...);
panel.revalidate();
panel.repaint();
You need to invoke the revalidate method to invoke the layout manager of the panel so the preferred size can be recalculated.
Edit:
newL.add(listPane);
You don't need the above statement. A Swing component can only have a single parent. That statement removed the panel from the scroll pane so you don't see the scroll bars.
newL.revalidate();
You don't need that statement. As I said in my answer you only need to revalidate() the panel that you changed.
Also you don't need all the statements below:
listPane.add(levelP);
listPane.revalidate();
listPane.repaint();
newL.add(listPane);
That is the layout manager is invoked when you pack the frame of make the frame visible. Your code should be:
newl.pack();
newl.setVisible(true);
That is you should only make the frame visible AFTER adding all the components to the frame.
I am developing Automated tests on Selenium Java and following is the configuration of my laptop.
Operating System:Windows 7 Ultimate.
Java Version:Java Version details
Eclipse Version:Eclipse IDE details
I am facing a problem with awt Choice component in java, as
when I open the choice drop down and click on 1st item, then it is not selected
then i select any other item from the list, and that item selected,
now when I select the first item again it is being selected.
Why it is not being selected on first click.
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Image;
public class MainMenu1 extends Frame implements ItemListener{
Choice bl;
String[][] userselect = new String[5][4];
MainMenu1() {
setTitle("Automation Test");
setLayout(null);setBackground(Color.pink);setSize(800,400); setLocation(200,200);setVisible(true);
setResizable(false);
bl = new Choice();bl.add("IE");bl.add("Chrome");bl.add("FireFox");bl.add("Safari");bl.add("Opera");bl.setSize(90, 21);bl.setLocation(180, 90);
add(bl);
bl.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent i){
if(i.getSource()==bl)
{
System.out.println(bl.getSelectedItem());
userselect[0][1]=bl.getSelectedItem();
}
}
public static void main(String[] args){
new MainMenu1();
}
}
I been using my textbook to build a GUI but one thing has been plaging me. When I try to make a clear button with a removeAll method it does not work at all. The problem I have been having is the GetActionCommand() is undefined .
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSlider;
import acm.program.GraphicsProgram;
import javafx.event.ActionEvent;
public class GUI_Program extends GraphicsProgram{
public void init() {
setBackground(Color.GRAY);
add(Cleared, WEST);
addActionListeners();
sizeSlider = new JSlider(MIN_SIZE, MAX_SIZE, INITIAL_SIZE);
add(new JLabel(" small"), WEST);
add(sizeSlider, WEST);
add(new JLabel("Large "), WEST);
ColorBox();
add(colorBox, WEST);
addMouseListeners();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Clear")) {
removeAll();
}
}
The problem is this line:
import javafx.event.ActionEvent;
There is more than one ActionEvent class, and this is the wrong one. Removing this line should fix the error. (The correct ActionEvent will then be imported by the line import java.awt.event.*; which you already have in your code.)
package com.objectplanet.chart.testing;
import java.math.*;
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import com.objectplanet.chart.*;
import java.awt.*;
import org.jfree.ui.RefineryUtilities;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
import java.util.EventListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
import com.objectplanet.chart.*;
import java.awt.*;
import javax.swing.filechooser.FileView;
import org.jfree.ui.RefineryUtilities;
import javax.swing.filechooser.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy;//this is for the dataset
import org.jfree.chart.plot.*;
import org.jfree.chart.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Paint;
import java.awt.Color;
import java.awt.BasicStroke;
//don't mind if here is too much libraries :)
/**
*
* #author Luka
*/
public class Test_english {
public static void main( String[] args ) {
double data[];
data = new double[12];
data[0] = 31;
data[1] = 28;
data[2] = 31;
data[3] = 30;
data[4] = 31;
data[5] = 30;
data[6] = 31;
data[7] = 31;
data[8] = 30;
data[9] = 31;
data[10] = 30;
data[11] = 31;
for(int i=1; i<12; i++){
System.out.println(data[i]);
}
//We have to make a Dataset
//show Dataset
//then we plug Dataset to graph
XYPlot graph=new XYPlot();
graph.setDataset(data);//This is the problem
graph.draw//why does this not working?
graph.Marker//Why is this not workig?
// We show graph and put markers
}
}
So i want to read data, make a graph and put markers. Then I am going to do some Gauss fit. I can read data, but i have a problem how to make dataset, make graph and do put markers. The library should be XYPlot and no else, because it puts markers too.
Regards, Luka
This question already has an answer here:
Is it possible to create programs in Java that create text to link in Chrome?
(1 answer)
Closed 10 years ago.
I'd like to make all links in JEditorPane clickable. I tried to use the code from this answer, but probably I've done something wrong because nothing happens when I click on the link. Here's my code:
JEditorPane news = new JEditorPane();
news.setSize(Size.L_NEWS);
news.setLocation(Position.L_NEWS);
news.setFocusable(false);
news.setBackground(new Color(255, 255, 255, 0));
news.setEditable(false);
news.setEnabled(false);
news.setOpaque(false);
news.setVisible(true);
news.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
news.setText(getNewsHTML.getNewestNews());
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){
e.printStackTrace();
}
news.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if(Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
}
catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
}
}
}
);
login_form.add(news);
And here - my imports(maybe they are the problem):
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
What is wrong? I don't have any output to Eclipse's console.
From my comments:
See my simple example here:
Your problem lies here:
news.setEnabled(false);
Dont set it to disabled or it wont be able to catch events like mouse click etc.
Also not sure why you have:
news.setFocusable(false);
news.setVisible(true);
The component does not need to be set visible just add to a container and make the container visible. Also dont make it unfocusable as this may cause problems later. Your setEditable(false) should be enough (as user wont be able to edit it regardless of focusabilty)