I'm trying to add a JList to a JPanel. Specifically, I have two JPanels, a right one and a left one. The right one has two buttons. On the left one I want the JList mySpriteOptions (see code below). Unfortunately, when I run my code, this JList never shows up. I'm no swing expert (in fact I'm a huge newb) so I can't figure out why this is.
Here is my code:
import java.awt.*;
import java.swing.*
public class SpriteEditorLauncher extends JFrame {
private JLabel mySearchBoxLabel;
private JList mySpriteOptions;
private JPanel myLeft;
private JPanel myRight;
private JScrollPane myScrollPane;
private JTextField mySearchBox;
private JButton myNewEditLauncher;
private JButton myEditLauncher;
private static final long serialVersionUID = 1L;
private static final String FONT_TYPE = "Times New Roman";
private static final int FONT_SIZE = 12;
private static final int FONT_STYLE = 1;
private static final Font FONT = new Font(FONT_TYPE, FONT_STYLE, FONT_SIZE);
private static final int NUMBER_OF_ROWS = 1;
private static final int NUMBER_OF_COLUMNS = 2;
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 400;
public SpriteEditorLauncher () {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initializeComponents();
createLayout();
}
private void initializeComponents () {
myLeft = new JPanel();
myRight = new JPanel();
myNewEditLauncher = new JButton();
myEditLauncher = new JButton();
myScrollPane = new JScrollPane();
mySpriteOptions = new JList();
mySearchBox = new JTextField();
mySearchBoxLabel = new JLabel();
}
private void setPanelBorder (JPanel toSetBorderFor) {
toSetBorderFor.setBorder(BorderFactory
.createTitledBorder(null, "Options", TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, FONT));
}
private void setButtonLabel (JButton button, Font font, String label) {
button.setFont(font);
button.setText(label);
}
private void setFrameLayout () {
GridLayout myLayout = new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS);
setLayout (myLayout);
setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
setResizable(false);
}
private void addPanelsToFrame () {
add(myLeft);
add(myRight);
}
private void addButtonsToPanel (JPanel panel) {
panel.add(myNewEditLauncher);
panel.add(myEditLauncher);
}
private void createLayout () {
setFrameLayout();
setPanelBorder(myRight);
setButtonLabel(myNewEditLauncher, FONT, "New");
setButtonLabel(myEditLauncher, FONT, "Edit");
addPanelsToFrame();
addButtonsToPanel(myRight);
mySpriteOptions.setModel(new AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] strings = { "Item 1", "Item 2"};
public int getSize () {
return strings.length;
}
public Object getElementAt (int i) {
return strings[i];
}
});
myLeft.add(mySpriteOptions);
myScrollPane.setViewportView(mySpriteOptions);
mySearchBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
mySearchBoxLabel.setFont(FONT);
mySearchBoxLabel.setLabelFor(mySearchBox);
mySearchBoxLabel.setText("Search:");
pack();
setVisible(true);
}
}
The default layout for a JPanel is FlowLayout.
FlowLayout likes to use the preferred size of it's components to layout them.
The default size a empty JList is probably 0x0, which means it never shows up.
Try creating the right panel with a BorderLayout (myRight = new JPanel(new BorderLayout());) and add the JList to it, wrapped in JScrollPane...
private void addPanelsToFrame () {
add(myLeft);
add(new JScrollPane(myRight));
}
Take a look at
Using Layout Managers
A Visual Guide to Layout Managers
For more information
You never add myScrollPane to the JPanel myLeft:
myLeft.add(myScrollPane);
Although you have added mySpriteOptions to myLeft, it is also set as the ViewportView of myScrollPane.
A component will only ever be painted on the last container to which it has been attached
—so will only appear in the JScrollPane, but this has not been added.
Now, this statement is not needed:
myLeft.add(mySpriteOptions);
Related
I'm trying to add a small tornado graphic (upside down pyramid) to my Frame. I can get the tornado by adding it to the frame in the main method but when I do that all I see is the tornado graphic and not the GUI underneath it.
So, I'm now trying to add the Tornado graphic to the frame when its created in the createComponents method but it now doesn't appear at all. Instead all I can see it the GUI in the frame.
I' probably missing something easy but I can't seem to figure it out. I'm not sure what I need to to in order to get the GUI and the tornado graphic both to appear.
public class EFScaleViewer {
public static void main(String[] args) {
// TODO Auto-generated method stub
TornadoFrame frame = new TornadoFrame();
frame.setTitle("EF Scale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here is where I create the frame and am trying to add the tornado:
public class TornadoFrame extends JFrame{
private JButton submit;
private JLabel label;
static JLabel errorLabel;
static JTextField textBox;
JPanel tornado = new TornadoComponent();
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
//Constructor for the frame
public TornadoFrame() {
super();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
createComponents();
}
private void createComponents()
{
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel panel = new JPanel();
panel.add(label);
panel.add(textBox);
panel.add(submit);
panel.add(errorLabel);
panel.add(tornado);
add(panel);
}
}
I know this is working but I may be missing something so here is where I create the tornado:
public class TornadoComponent extends JPanel {
public void paintComponent(Graphics g) {
int[] xPoints = {100,200,0};
int[] yPoints = {0,200,200};
int nPoints = 3;
g.drawPolygon(xPoints, yPoints, nPoints);
}
}
You have to set the JPanels size for it to be able to display Graphics.
static class TornadoComponent extends JPanel {
public TornadoComponent() {
setPreferredSize(new Dimension(500, 500));
}
#Override
public void paintComponent(Graphics g) {
//Whatever
}
}
And in order to trigger paintComponent(Graphics g) you have to add tornado.repaint(); at the end of your createComponents() function.
private void createComponents() {
//All your components
panel.add(tornado);
add(panel);
tornado.repaint();
}
Now the Polygon is shown but not at the right place (slightly off the image)
Therefore we have to arrange your JPanels a bit:
private void createComponents() {
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel upper = new JPanel();
upper.setLayout(new BoxLayout(upper,BoxLayout.X_AXIS));
upper.add(label);
upper.add(textBox);
upper.add(submit);
upper.add(errorLabel);
JPanel lower = new JPanel();
lower.setLayout(new BoxLayout(lower,BoxLayout.X_AXIS));
lower.add(tornado);
JPanel over = new JPanel();
over.setLayout(new BoxLayout(over,BoxLayout.Y_AXIS));
over.add(upper);
over.add(lower);
add(over);
tornado.repaint();
}
Basically I make some boxes...
Over
Upper
... your stuff with text
Lower
Our tornado
Now our tornado is the wrong way round...
int[] xPoints = {100,200,150};
int[] yPoints = {0,0,150};
And voilà:
We just created a very basic tornado that is not aiming at anything :)
If you want to change the tornados position later you just have to recall tornado.repaint(); and you are all set.
I have a desktop application in swing. I have a JPanel in which the image as the background and in it two buttons and a JScrollPane as shown in the picture Frame with JPanel. I have a function (showLabel()) which, when JScrollPane the end, add JLabel with transparent images and disappear a few seconds. The problem is that when you add JLabel. JLabel bad shows as seen in Fig Bad shows. Can you help me with my problem?
public class MainWindow {
private JFrame frame;
private PanelPopis panelPopis = new PanelPopis(this);
private MyPaint myPaint;
public MainWindow {
setWindow():
BufferedImage image1 = ImageIO.read(getClass().getClassLoader().getResource("poz.png"));
this.myPaint = new MyPaint(image1);
this.frame.add(myPaint);
this.myPaint.add(panelPopis.setPanel());
}
private void setWindow() {
this.frame = new JFrame("DD");
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setSize(400, 680);
this.frame.setResizable(false);
this.frame.setLocationRelativeTo(null);
}
private void showLabel(){
JLabel label = new JLabel();
label.setIcon(new ImageIcon(new ImageIcon(getClass().getClassLoader().getResource("postEn.png")).getImage().getScaledInstance(395, 653, Image.SCALE_DEFAULT)));
label.setBackground(new Color(0, 0, 0, 10));
label.setOpaque(true);
this.frame.invalidate();
this.frame.add(label);
this.frame.revalidate();
int delay2 = 3000; // milliseconds
ActionListener taskPerformer2 = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.remove(label);
frame.revalidate();
frame.repaint();
}
};
Timer myTimer2 = new Timer(delay2, taskPerformer2);
myTimer2.setRepeats(false);
myTimer2.start();
}
}
public class MyPaint extends JPanel {
private static final long serialVersionUID = 1L;
BufferedImage image;
public MyPaint(BufferedImage image) {
setOpaque(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 395, 653, this);
}
}
public class PanelPopis extends JPanel {
private static final long serialVersionUID = 7676683627217636485L;
private JButton setLanguage;
private JButton cont;
private JScrollPane scrolPanel;
private JTextArea popis;
private MainWindow mainWindow;
public PanelPopis(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
public JPanel setPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setOpaque(false);
JPanel panel2 = new JPanel();
Border border = panel2.getBorder();
Border margin = new EmptyBorder(0, 0, 4, 0);
panel2.setBorder(new CompoundBorder(border, margin));
panel2.setOpaque(false);
panel2.add(this.scrolPanel = new JScrollPane(popis));
panel.add(this.setLanguage = new JButton("language settings"), BorderLayout.NORTH);
panel.add(this.cont = new JButton("CONTINUE"), BorderLayout.SOUTH);
panel.add(panel2, BorderLayout.CENTER);
return panel;
}
}
I would suggest to use the getResource() method instead of the getResourceAsStream() and have the path of both images inputted there this way.
The classLoader could behave differently (in your case due to the differences between the two OS's) so doing it this way would guarantee that you application is always getting the correct resources.
More on the getResource here:
https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
I am in the early stages of trying to create a Java 2d graphics paint program. I'm using a flow layout, and I'm using three panels. The first two are rows of buttons, combo boxes, etc. and the third is meant to be a large, blank, white panel that will be used to paint on. The first two panels show up beautifully, but the paint panel appears as a small white box next to the second button panel. Any help would be appreciated.
public class DrawingApp extends JFrame
{
private final topButtonPanel topPanel = new topButtonPanel();
private final bottomButtonPanel bottomPanel = new bottomButtonPanel();
private final PaintPanel paintPanel = new PaintPanel();
public DrawingApp()
{
super("Java 2D Drawings");
setLayout(new FlowLayout());
add(topPanel);
add(bottomPanel);
add(paintPanel);
}
public static void main(String[] args)
{
DrawingApp frame = new DrawingApp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(750,500);
frame.setVisible(true);
}
}
public class topButtonPanel extends JPanel
{
private final String[] names = {"Line", "Oval", "Rectangle"};
private final JButton undo = new JButton("Undo");
private final JButton clear = new JButton("Clear");
private final JLabel shape = new JLabel("Shape:");
private final JComboBox<String> shapesComboBox = new JComboBox(names);
private final JCheckBox filled = new JCheckBox("Filled");
public topButtonPanel()
{
super();
setLayout(new FlowLayout());
add(undo);
add(clear);
add(shape);
shapesComboBox.setMaximumRowCount(3);
add(shapesComboBox);
add(filled);
}
}
public class bottomButtonPanel extends JPanel
{
private final JCheckBox useGradient = new JCheckBox("Use Gradient");
private final JButton firstColor = new JButton("1st Color");
private final JButton secondColor = new JButton("2nd Color");
private final JLabel lineWidthLabel = new JLabel("Line Width:");
private final JLabel dashLengthLabel = new JLabel("Dash Length:");
private final JTextField lineWidthField = new JTextField(2);
private final JTextField dashLengthField = new JTextField(2);
private final JCheckBox filled = new JCheckBox("Dashed");
public bottomButtonPanel()
{
super();
setLayout(new FlowLayout());
add(useGradient);
add(firstColor);
add(secondColor);
add(lineWidthLabel);
add(lineWidthField);
add(dashLengthLabel);
add(dashLengthField);
add(filled);
}
}
public class PaintPanel extends JPanel
{
public PaintPanel()
{
super();
setBackground(Color.WHITE);
setSize(700,400);
}
}
Basically, it's a misunderstanding of how the Swing API works.
Swing relies (heavily) on the layout management API which is used to make decisions about how large components should be (and where they should be placed)
Using setSize is pointless, as the layout manager will make it's own decisions about what it thinks the size of your component should be and will adjust it accordingly.
You can make suggestions to the layout manager about how large you'd like the component to be using getPreferred/Minimum/MaximumSize, for example
public class PaintPanel extends JPanel
{
public PaintPanel()
{
super();
setBackground(Color.WHITE);
}
public Dimension getPreferredSize() {
return new Dimension(700, 400);
}
}
Just remember, layout managers are well within their right to ignore these values, so you need to have a better understanding of how these managers work
See Laying Out Components Within a Container for more details
I am trying to make a JTextArea vertically scrollable. I did some research and I'm pretty sure I'm using a LayoutManager, not adding JTextArea directly to the parent panel, and is setting the preferred size of both JTextArea and JScrollPane. Not sure what am I missing here... Here's the code:
public class ConsolePane extends JDialog {
private static final long serialVersionUID = -5034705087218383053L;
public static final Dimension CONSOLE_DIALOG_SIZE = new Dimension(400, 445);
public static final Dimension CONSOLE_LOG_SIZE = new Dimension(400, 400);
public static final Dimension CONSOLE_INPUT_SIZE = new Dimension(400, 25);
private static ConsolePane instance = new ConsolePane();
public static ConsolePane getInstance() {
return instance;
}
private JTextArea taLog;
private JTextField tfInput;
public ConsolePane() {
this.setTitle("Console");
JPanel contentPane = new JPanel();
this.setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
contentPane.add(createConsoleLog(), BorderLayout.CENTER);
contentPane.add(createConsoleInput(), BorderLayout.SOUTH);
contentPane.setPreferredSize(CONSOLE_DIALOG_SIZE);
}
private JComponent createConsoleLog() {
taLog = new JTextArea();
taLog.setLineWrap(true);
taLog.setPreferredSize(CONSOLE_LOG_SIZE);
((DefaultCaret) taLog.getCaret())
.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane container = new JScrollPane(taLog);
container
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
container
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
container.setPreferredSize(CONSOLE_LOG_SIZE);
return container;
}
private JComponent createConsoleInput() {
tfInput = new JTextField();
tfInput.setPreferredSize(CONSOLE_INPUT_SIZE);
tfInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
taLog.append(tfInput.getText() + "\r\n");
tfInput.setText("");
}
});
tfInput.requestFocus();
return tfInput;
}
public static void main(String[] args) {
ConsolePane.getInstance().pack();
ConsolePane.getInstance().setVisible(true);
}
}
Thx in advance!
Try the following code, It may help you
JTextArea txt=new JTextArea();
JScrollPane pane=new JScrollPane(txt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Figured it out myself. taLog.setPreferredSize() is preventing the scrolling. removed that and everything worked fine. Thx everyone for your help.
I'm having trouble getting a JPanel inside a BorderLayout to work.
I defined the layout of the Panel as a Grid Layout, and then added a bunch of buttons I had made before hand to the JPanel. However, when I run the program, the JFrame loads but nothing within the frame loads. Here's the code:
import java.awt.*;
import javax.swing.*;
public class Phone extends JFrame {
private JTextField PhoneText;
private JPanel ButtonPanel;
private JButton bttn1;
private JButton bttn2;
private JButton bttn3;
private JButton bttn4;
private JButton bttn5;
private JButton bttn6;
private JButton bttn7;
private JButton bttn8;
private JButton bttn9;
private JButton bttn10;
private JButton bttn11;
private JButton bttn12;
public Phone(){
setTitle("Phone - Agustin Ferreira");
Container ContentPane = getContentPane();
ContentPane.setLayout(new BorderLayout());
setSize(300, 400);
setVisible(true);
setBackground(Color.DARK_GRAY);
PhoneText = new JTextField("(317)188-8566");
bttn1 = new JButton ("1");
bttn2 = new JButton ("2");
bttn3 = new JButton ("3");
bttn4 = new JButton ("4");
bttn5 = new JButton ("5");
bttn6 = new JButton ("6");
bttn7 = new JButton ("7");
bttn8 = new JButton ("8");
bttn9 = new JButton ("9");
bttn10 = new JButton ("*");
bttn11 = new JButton ("0");
bttn12 = new JButton ("#");
ButtonPanel = new JPanel(new GridLayout(4,3,0,0));
ButtonPanel.add(bttn1);
ButtonPanel.add(bttn2);
ButtonPanel.add(bttn3);
ButtonPanel.add(bttn4);
ButtonPanel.add(bttn5);
ButtonPanel.add(bttn6);
ButtonPanel.add(bttn7);
ButtonPanel.add(bttn8);
ButtonPanel.add(bttn9);
ButtonPanel.add(bttn10);
ButtonPanel.add(bttn11);
ButtonPanel.add(bttn12);
ContentPane.add(PhoneText, BorderLayout.NORTH);
ContentPane.add(ButtonPanel, BorderLayout.CENTER);
}
}
Additionally, I have another class that calls the Phone class. Here's the code for that, just in case:
package ProgrammingAssignment11;
import javax.swing.JFrame;
public class GUI_Driver {
public static void main(String[] args) {
Phone Nokia;
Nokia = new Phone();
Nokia.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
Any Help?
Much appreciated, M3tal T1ger
Your main problem:
You should only call setVisible(true) after adding components to your GUI. You don't do this and so the GUI gets drawn without its components.
Also:
You should avoid setting the sizes or preferred sizes of anything. Instead let the components and layout managers size themselves.
And don't forget to call pack() after adding all components and before making the GUI visible.
Learn and follow Java naming conventions, including giving all variables and methods names that begin with a lower case letter, and all classes with names that start with an upper-case letter.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Phone2 extends JPanel {
private static final String[][] BTN_TEXTS = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"*", "0", "#"}
};
private static final float BTN_POINTS = 48f;
private static final float TEXT_POINTS = 24f;
private static final int DISPLAY_COLUMNS = 12;
private JButton[][] buttons = new JButton[BTN_TEXTS.length][BTN_TEXTS[0].length];
private JTextField display = new JTextField(DISPLAY_COLUMNS);
public Phone2() {
display.setFocusable(false);
display.setFont(display.getFont().deriveFont(TEXT_POINTS));
GridLayout gridLayout = new GridLayout(BTN_TEXTS.length, BTN_TEXTS[0].length);
JPanel btnPanel = new JPanel(gridLayout);
for (int i = 0; i < BTN_TEXTS.length; i++) {
for (int j = 0; j < BTN_TEXTS[i].length; j++) {
String text = BTN_TEXTS[i][j];
JButton btn = new JButton(new BtnAction(text));
btn.setFont(btn.getFont().deriveFont(Font.BOLD, BTN_POINTS));
btnPanel.add(btn);
buttons[i][j] = btn;
}
}
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(btnPanel, BorderLayout.CENTER);
}
private class BtnAction extends AbstractAction {
public BtnAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
String text = evt.getActionCommand();
display.setText(display.getText() + text);
}
}
private static void createAndShowGui() {
Phone2 mainPanel = new Phone2();
JFrame frame = new JFrame("Phone");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}