Border with spacing in Java? - java

I'm trying to make a border, which as been successful. I want there to be some spacing before the border starts. Using this code now, the border is wrapped very tight around the text box. This is what I want to do: Ideal
public static void main(String[] args) {
// TODO code application logic here
//Variables
JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
JPanel cards = new JPanel(new CardLayout());
CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createLineBorder(Color.black));
TextPaneScreen1.setMargin(new Insets(3,3,3,3));
screen1.add(TextPaneScreen1);
cards.add(screen1);
mainframe.add(cards);
mainframe.setVisible(true);
}

Try creating a compound border with your line border and an empty border:
BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),
BorderFactory.createEmptyBorder(5, 5, 5, 5))

Related

Java Swing Scrollpane not scrolling

I want to be able to scroll down a dynamically generated list of movies. I tried adding a Scrollpane.
I have a navigation bar at the page start and in the center a jpanel with all the movies.
You can recreate this example by using this code:
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
// MoviePanel Class
public static JPanel createMoviePanel() {
JPanel parentMoviePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 25));
JPanel contentPanel = new JPanel(new GridLayout(0, 1));
JPanel moviePanel = new JPanel(new GridLayout(0, 9, 8, 5));
JScrollPane scrollPane = new JScrollPane(moviePanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
parentMoviePanel.setBackground(new Color(32, 32, 32));
contentPanel.setBackground(new Color(32, 32, 32));
moviePanel.setBackground(new Color(32, 32, 32));
final File root = new File("");
for (int i = 0; i < 70; i++) {
// Get the image and scale it down
BufferedImage movieCover=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)movieCover.getGraphics();
g2d.setColor(Color.GRAY);
g2d.fillRect(0,0,movieCover.getWidth(),movieCover.getHeight());
// Create button and change settings
JButton movieButton = new JButton("Movie " + i, new ImageIcon(movieCover));
movieButton.setMargin(new Insets(0, 0, 0, 0));
movieButton.setPreferredSize(new Dimension(180, 250));
movieButton.setForeground(Color.WHITE);
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
movieButton.setHorizontalTextPosition(JButton.CENTER);
movieButton.setVerticalTextPosition(JButton.BOTTOM);
moviePanel.add(movieButton);
scrollPane.revalidate();
}
contentPanel.add(moviePanel);
contentPanel.add(scrollPane);
parentMoviePanel.add(contentPanel);
return parentMoviePanel;
}
// Navbar Class
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
What I'm trying to do is to scroll down this list of movies, using my mouse wheel without seeing any kind of scrollbar. It should look exactly how it looks now, but I want to be able to scroll down and see all the movies.
I don't know why it isn't working that's why I'm asking here in hope someone can explain to me what I'm doing wrong.
Your usage of a scroll pane is incorrect.
A Swing component can only have a single parent. The following code is creating the scroll pane with a child component. However you then remove the moviePanel from the scroll pane when you add it to the content pane.
So the scroll pane has no child component and will never work.
JScrollPane scrollPane = new JScrollPane(moviePanel);
...
contentPanel.add(moviePanel);
contentPanel.add(scrollPane);
However, even that won't solve your problem because you are now using a FlowLayout on your top level panel so all the child components will always be displayed at their preferred size so there is no need for scroll bars.
Get rid of all the scroll pane logic in your createMoviePanel() method.
Instead you probably want to add the scroll pane to the content pane:
//frame.add(moviePanel, BorderLayout.CENTER);
frame.add(new JScrollPane(moviePanel), BorderLayout.CENTER);
Now the scroll pane will dynamically resize as the frame size changes. Scrollbars will then appear as required.

How to make a border fit around a JLabel

I would like to make my JLabel have a border which fits around the text. I have tried using ints to resize but that doesn't work. Can anyone help?
Here is my Java code:
package first;
import java.awt.*;
import javax.swing.*;
public class TopLevelWindow {
static int hgap=5;
static int vgap=5;
private static void createWindow() {
//Create and set up the window.
JFrame frame = new JFrame("Window");
JLabel textLabel = new JLabel("Welcome Child",SwingConstants.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
textLabel.setForeground(Color.YELLOW);
textLabel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5));
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args) { createWindow(); }
}
I would want it to look like the text box in this:
http://www.bogleech.com/halloween/undertale-grillbys.png
is that possible in java?
Obviously, if you set your JLabel’s size to 300×300, its border will be around that rectangle.
Instead, leave the JLabel’s size alone, and place it inside a panel with a centering layout, then place the border on that panel:
JLabel textLabel = new JLabel("Welcome Child",SwingConstants.CENTER);
textLabel.setForeground(Color.YELLOW);
textLabel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5));
JPanel textPanel = new JPanel(new GridBagLayout());
textPanel.add(textLabel);
textPanel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textPanel, BorderLayout.CENTER);
If you want to achieve the effect from the screen you should set the vertical alignment to NORTH and use CompoundBorder consisting of white outer border and inner invisible border which looks like the margin. Try this piece of code:
JLabel textLabel = new JLabel("Test test test test test test test...");
textLabel.setPreferredSize(new Dimension(500, 250));
textLabel.setForeground(Color.WHITE);
textLabel.setFont(new Font("Courier", Font.BOLD, 30));
// sets the text to the upper left corner
textLabel.setVerticalAlignment(SwingConstants.NORTH);
textLabel.setBorder(new CompoundBorder( // sets two borders
BorderFactory.createMatteBorder(10, 10, 10, 10, Color.WHITE), // outer border
BorderFactory.createEmptyBorder(10, 10, 10, 10))); // inner invisible border as the margin

Multiple documents with the same JTable

I am developing a Java Application that uses a JTable for capturing user input. The user will have to print data captured in the table. I would want the user to open multiple documents to work on. This I have implemented it this way: I have my JFrame as my main window; on to this JFrame, I have added JTabbedPane so that the user can switch between File, Settings and Tools.Upon clicking new File, the user is taken to a JTabbedPane(place at the center of the JFrame) with a JTable for input. I would want that the next time the user click new File, a new JPanel would be added to the JTabbledPane; but this new JPanel should also contain the JTable for input.This behavior should continue everytime the user creates a new File. This is shown in the images that I have uploaded.(Please forgive for poor drawing).
I have achied this by this code:
public final class QuotPane {
//components to be used
JFrame frame;
JTabbedPane tabbedPane,tablePane;
JPanel quotPane, topPane, pane1, pane2, pane3,tablePanel;
JSeparator sep;
JButton newFile;
QuotPane() {
this.createQuotPane();
this.createGUI();
ButtonActionListener lits= new ButtonActionListener();
newFile.addActionListener(lits);
}
public void createGUI() {
tabbedPane = new JTabbedPane();
tabbedPane.addTab("Create Quot", quotPane);
frame = new JFrame("Qout Interface");
frame.setSize(new Dimension(700, 650));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
//adding the tabbed pane to the frmae
frame.add(tabbedPane, BorderLayout.NORTH);
}
public void createQuotPane() {
quotPane = new JPanel();
quotPane.setLayout(new BorderLayout());
//creating the top pane
topPane = new JPanel();
topPane.setPreferredSize(new Dimension(650, 145));
topPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.lightGray, Color.lightGray, Color.white, Color.orange));
topPane.setLayout(new MigLayout());
//add the top pane on the quot panel
quotPane.add(topPane, BorderLayout.NORTH);
//adding the panes on the top pane
this.createPanels();
topPane.add(pane1);
topPane.add(pane2);
topPane.add(pane3);
}
//a method to create panes for options
public void createPanels() {
pane1 = new JPanel();
pane1.setPreferredSize(new Dimension(200, 140));
pane1.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.BLUE, Color.lightGray, Color.white, Color.orange));
//lets set the icons then
pane1.setLayout(new MigLayout());
Icon fileIcon = new ImageIcon(this.getClass().getResource("/images/fil.jpg"));
newFile = new JButton(fileIcon);
pane1.add(new JLabel("New File"), "wrap");
pane1.add(newFile,"width 20!");
pane2 = new JPanel();
pane2.setPreferredSize(new Dimension(200, 140));
pane2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.BLUE, Color.lightGray, Color.white, Color.orange));
pane3 = new JPanel();
pane3.setPreferredSize(new Dimension(200, 140));
pane3.setMaximumSize(new Dimension(300, 140));
pane3.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.BLUE, Color.lightGray, Color.white, Color.orange));
}
public static void main(String[] args) {
QuotPane qp = new QuotPane();
}
public void createTablePane(){
tablePanel= new JPanel();
}
class ButtonActionListener implements ActionListener{
protected int count=0;
#Override
public void actionPerformed(ActionEvent e) {
if(count==0){
if(e.getSource().equals(QuotPane.this.newFile)){
tablePane=new JTabbedPane();
QuotPane.this.createTablePane();
tablePane.addTab("New Qout", tablePanel);
frame.add(tablePane,BorderLayout.CENTER);
count ++;
}
}else if(count>0)
{
tablePane.add("New Quote",new JPanel());
}}}}
The challenge I am facing here is that I cannot add my JTable to every panel created at run time.I have tried this: tablePane.add("New Quote",myCreatedBeforePanleWithTable) but it is overriding the previous tab.
Here are images of things that I want.I read about JDeskTopPane and JInternalFrame, but can't figure out how to make it work the way I want.
How do I make it work the way I want as shown in the image?
Unfortunately, a Swing Component can only have a single parent. If you add Component A to JPanel X and then to JPanel Y, it will end up in Y.
You will need to have three separate JTables, all sharing a single TableModel. This should be fairly straightforward to implement the basic functionality. It might get tricky if you allow sorting and column reordering and you want that to affect all 3 tables.

Runtime error when implementing Java gui sliders

My first time posting a question here. Been coming here a while and enjoyed reading the threads. Was hoping someone on here could help me with a program I've been doing to learn Java. The program calls to implement sliders to change the background color in a gui background. It compiles fine, but when I run it, I get a few errors, which I commented in at the end of the code.
Code is as follows:
import java.awt.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.*;
public class sliderDemo extends JFrame
{
private JSlider redSlider, greenSlider, blueSlider;
private JPanel labels, sliders, colors;
private JLabel redlabel,greenlabel, bluelabel, colorlabel;
JTextArea colorPanel;
public sliderDemo()
{
setTitle("Slider Excercise");
setLayout(new BorderLayout(5, 5));
ChangeListener event = new eventListener();
colorlabel = new JLabel("Sliders to change colors:");
redlabel = new JLabel("Red slider");
greenlabel = new JLabel("Green slider");
bluelabel = new JLabel("Blue slider");
labels = new JPanel();
labels.setLayout(new GridLayout(3,1));
labels.add(redlabel);
labels.add(greenlabel);
labels.add(bluelabel);
redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
redSlider.addChangeListener(event);
redSlider.setMaximum(255);
redSlider.setPaintLabels(true);
redSlider.setPaintTicks(true);
redSlider.setMajorTickSpacing(25);
redSlider.setMinorTickSpacing(5);
redSlider.setPaintTrack(false);
greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
greenSlider.addChangeListener(event);
greenSlider.setMaximum(255);
greenSlider.setPaintLabels(true);
greenSlider.setPaintTicks(true);
greenSlider.setMajorTickSpacing(25);
greenSlider.setMinorTickSpacing(5);
greenSlider.setPaintTrack(false);
blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
blueSlider.addChangeListener(event);
blueSlider.setMaximum(255);
blueSlider.setPaintLabels(true);
blueSlider.setPaintTicks(true);
blueSlider.setMajorTickSpacing(25);
blueSlider.setMinorTickSpacing(5);
blueSlider.setPaintTrack(false);
sliders = new JPanel();
sliders.setLayout(new GridLayout(3,1));
sliders.add(colorlabel);
sliders.add(redSlider);
sliders.add(greenSlider);
sliders.add(blueSlider);
colorPanel = new JTextArea(10, 10);
colorPanel.setEditable(false);
colorPanel.setBackground(Color.WHITE);
colorPanel.add(sliders, BorderLayout.CENTER);
colorPanel.add(colors, BorderLayout.NORTH);
colorPanel.add(labels, BorderLayout.WEST);
colors = new JPanel(new BorderLayout(5, 5));
colors.add(colorlabel);
colors.add(colorPanel, BorderLayout.NORTH);
}
public static void main(String[] args)
{
JFrame myFrame = new sliderDemo();
myFrame.setSize(500, 500);
myFrame.setVisible(true);
myFrame.setLocationRelativeTo(null);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class eventListener implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
int r = redSlider.getValue();
int g = greenSlider.getValue();
int b = blueSlider.getValue();
colorPanel.setBackground(new Color(r, g, b));
}
}
}
/*
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1090)
at java.awt.Container.add(Container.java:966)
at sliderDemo.<init>(sliderDemo.java:79)
at sliderDemo.main(sliderDemo.java:89)
Press any key to continue . . .
add JComponents that are initialized
you tried to add JPanel colors to JTextArea (quite nonsence) and its intialization colors = new JPanel(new BorderLayout(5, 5)); is in the next code lines
rename JTextArea colorPanel; to JTextArea textArea
then you miss 4th JPanel, because JTextArea colorPanel is called textArea and JTextArea isn't container for JPanels, is designated for user keys input
As mKorbel answer is not yet ticked as solution I will try to make it clearer (probably to late anyway):
In the lines
colorPanel.add(sliders, BorderLayout.CENTER);
colorPanel.add(colors, BorderLayout.NORTH);
colorPanel.add(labels, BorderLayout.WEST);
you add your JPanels to your text area that was meant for the color display (as mentioned by mKobel you should choose a better name). Remove the leading "colorPanel.". That will add the panels to the main panel instead (as was intended).
Also you have to move
colors = new JPanel(new BorderLayout(5, 5));
colors.add(colorlabel);
colors.add(colorPanel, BorderLayout.NORTH);
in front of the first code snippet as "colors" has to be instantiated first, before you add it to the layout.
After those changes the program is working (tested it myself). :)

Resize makes things wrong

I want to create a JInternalFrame with some components in it.
My aim is to design a bash console in Java.
My frame is made of 4 components:
JTextArea included into a JScrollPane
JLabel with the text "Cmd:"
JTextField
JButton with the text "Send"
And I have the following code:
Box box = Box.createHorizontalBox();
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_label);
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_input);
box.add(Box.createVerticalStrut(5));
box.add(this.submit);
box.add(Box.createVerticalStrut(5));
Box mainBox = Box.createVerticalBox();
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(this.result_scroll);
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(box);
mainBox.add(Box.createHorizontalStrut(5));
add(mainBox);
So when the frame has not been maximized, I have a correct look:
But when I maximize it, all components are incorrectly located:
So, here is my question: How can I set a weight to the components to fix their location every time, or, how can I fix it?
Thanks.
I think this would be better done with a BorderLayout. In a BorderLayout, the component specified as the center component will expand to fill as much space as possible, and the other components will remain at their preferred sizes.
int hgap = 5;
int vgap = 5;
internalFrame.getContentPane().setLayout(new BorderLayout(hgap, vgap));
internalFrame.getContentPane().add(this.result_scroll, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.add(this.cmd_label);
bottomPanel.add(this.cmd_input);
bottomPanel.add(this.submit);
internalFrame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
Here try this code, is this behaviour exceptable :
import java.awt.*;
import javax.swing.*;
public class LayoutExample
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("LAYOUT EXAMPLE");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JTextArea tarea = new JTextArea(10, 10);
tarea.setBackground(Color.DARK_GRAY.darker());
tarea.setForeground(Color.WHITE);
tarea.setCaretColor(Color.WHITE);
tarea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(tarea);
centerPanel.add(scrollPane, BorderLayout.CENTER);
JPanel footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout(5, 5));
footerPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JLabel cmdLabel = new JLabel("Cmd : ");
JTextField tfield = new JTextField(10);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JButton sendButton = new JButton("SEND");
footerPanel.add(cmdLabel, BorderLayout.LINE_START);
footerPanel.add(tfield, BorderLayout.CENTER);
buttonPanel.add(sendButton);
footerPanel.add(buttonPanel, BorderLayout.LINE_END);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
frame.getContentPane().add(footerPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutExample().createAndDisplayGUI();
}
});
}
}
OUTPUT :
Base problem here is what I consider a bug in JTextField's max layout hint: it's unbounded in both horizontal and vertical dimension. The latter is pure nonsense for a component designed for showing a single line of text. To fix, subclass and let it return its pref for the height, like:
JTextField cmdInput = new JTextField() {
#Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
As BoxLayout respects maxSize, the excess height now will be given to the top box only.
On the long run, consider switching to a third party manager which allows fine-tuning in a all-in-one-panel approach. Yeah, here comes my current favourite: MigLayout. Compare the following lines to all the nesting and border tricks above and have fun :-)
MigLayout layout = new MigLayout("wrap 3, debug",
"[][grow, fill][]", // 3 columns, middle column filled and allows growing
"[grow, fill][]"); // two rows, first filled and allows growing
JComponent content = new JPanel(layout);
// the scrollPane in the first row spanning all columns
// and growing in both directions
content.add(new JScrollPane(new JTextArea(20, 20)), "span, grow");
// auto-wrapped to first column in second row
content.add(new JLabel("Cmd:"));
content.add(new JTextField());
content.add(new JButton("Submit"));

Categories